Unity3D, C#:将函数名称另存为变量
本文关键字:另存为 变量 函数 Unity3D | 更新日期: 2023-09-27 18:34:25
我正在使用Unity3D并尝试实现以下目标。我想在类中存储一些参数以及"特殊规则" - 这是这个或其他类中的函数。
理想情况下,我想要这样的东西:
public class Weapon
{
public DamageHandler damageHandler; //script that have all special rule functions
public string weaponName;
public int damage;
public ???? specialRule; //this is the rule of interest
public void DealDamage()
{
damageHandler = GetComponent<DamageHandler>();
damageHandler.specialRule(damage); //call the function that is set in Weapon Class
}
}
我知道我可以将 specialRule 保存为字符串并使用反射。有没有其他方法/更好的方法来处理这种情况?
你要找的是我朋友Action<int>
。
public class Weapon
{
public DamageHandler damageHandler; //script that have all special rule functions
public string weaponName;
public int damage;
public Action<int> specialRule; //this is the rule of interest
public void DealDamage()
{
damageHandler = GetComponent<DamageHandler>();
damageHandler.specialRule(damage); //I call the function with the name that is set in Weapon Class
}
}
Action<ParamType1, ParamType2, ParamType3, .....>
表示void
函数委托。
Func<ParamType1, ParamType2, ParamType3, ....., ReturnType>
表示具有返回值的函数
每个都可以采用 1 或 2 个类型参数,我相信大约 17 个左右