2016-02-11 136 views
0

我正在使用Unity3D并尝试实现以下功能。 我想在该类中存储一些参数以及“特殊规则” - 哪些是这个或其他类中的函数。Unity3D,C#:将函数名称保存为变量

理想我想的东西,行为是这样的:我知道我可以specialRule保存为一个字符串,并使用反射

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 
    }   
} 

。有没有其他方式/更好的方法来处理这种情况?

回答

4

你在找什么是我的朋友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个左右

+0

非常感谢您! – Alex

+0

这里是一个壮观的相关答案... http://stackoverflow.com/a/35343428/294884 – Fattie

相关问题