我想创建一个动态条件语句。
class Condition
{
targetObject; //Class or Struct or anythings..
targetMemberVariable; //the Member in targetObject
conditionFilter;
//It depends on the type of targetMemberVariable.
//targetMemberVariable is Float type,
//then conditionFilter automatically becomes a Float type.
//No need to change it in "Inspector"
comparisonValue;
//This is based on the type of conditionFilter.
//If it is a float type, the "Inspector" takes a float as its value.
Public bool CheckCondition(object targetObject)
{
//It checks with the above information and returns a true value.
return true or false;
}
}
我想获得Unity Editor或C#库关键字。
目的是创造类似上述内容。
例如
ex1 ex2 我记得在C#中使用动态编译时或在执行期间添加类之后看到了库。
当然我知道动态并不普遍。 我想做一些像星际争霸Galaxy Editor的验证。
这是一个游戏示例
[Bleeding shot]
Give 10 damage to enemies.
If the enemy's Health is below 20, it adds 10 damage.
unit,health,amount,<=(below)
true-> adds 10 damage.
false -> none.
[Hooking]
If the enemy is enemy, it gives 5 damage and pulls to the front.
If the target is ally, pull to the front and reduce cooldown to 5 seconds.
unit,Tag,Enemy(enum),==
true-> 5 damage and pulls to the front.
false-> pull to the front and reduce cooldown to 5 seconds.
[Healing the Moon]
Heal the target by 10.
If the current time is night, heal 10 more.
GameTimer,DayNight(Enum),Night,==
true->heal 10 more.
答案 0 :(得分:2)
制作这种通用可能会有所帮助,因为被测试的类型各不相同。这样,您的CheckCondition
方法就是类型安全的。
你可以从界面开始。在未来的道路上,您可能需要一种比仅将特定成员与某个阈值进行比较更复杂的条件。
public interface ICondition<T>
{
bool CheckCondition(T subject);
}
我怀疑在大多数情况下,你会发现明确检查条件比在类中存储成员信息更容易使用反射。
例如,
public class SomeClass
{
public int Value { get; set; }
}
public class MinimumValueCondition : ICondition<SomeClass>
{
public bool CheckCondition(SomeClass subject)
{
return subject.Value > 5;
}
}
它非常容易阅读,无需反思。如果评估条件所需的某些数据是可变的,则可以将其传入。
public class MinimumValueCondition : ICondition<SomeClass>
{
private readonly int _minimumValue;
public MinimumValueCondition(int minimumValue)
{
_minimumValue = minimumValue;
}
public bool CheckCondition(SomeClass subject)
{
return subject.Value >= _minimumValue;
}
}
您还可以编写一个以函数作为参数的条件。
public class Condition<T> : ICondition<T>
{
private readonly Func<T, bool> _conditionFunction;
public Condition(Func<T, bool> conditionFunction)
{
_conditionFunction = conditionFunction;
}
public bool CheckCondition(T subject)
{
return _conditionFunction(subject);
}
}
这样你就可以从表达式或方法中创建Condition
。
var notZeroCondition = new Condition<SomeClass>(subject => subject.Value != 0);
var someOtherCondition = new Condition<SomeClass>(SomeEvaluationMethod);