【问题标题】:Unity3D, C#: Save function name as variableUnity3D,C#:将函数名称保存为变量
【发布时间】:2016-02-12 06:07:53
【问题描述】:

我正在使用 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 保存为字符串并使用反射。有没有其他方法/更好的方法来处理这种情况?

【问题讨论】:

    标签: c# function unity3d


    【解决方案1】:

    你要找的是Action&lt;int&gt;我的朋友。

    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&lt;ParamType1, ParamType2, ParamType3, .....&gt; 表示 void 函数委托。

    Func&lt;ParamType1, ParamType2, ParamType3, ....., ReturnType&gt;代表一个有返回值的函数

    每个都可以采用 1 或 2 个类型参数,我相信大约 17 个左右

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 2018-11-04
    • 2016-04-27
    相关资源
    最近更新 更多