【问题标题】:Unity - SendMessage but for variable instead of function/methodUnity - SendMessage,但用于变量而不是函数/方法
【发布时间】:2018-10-04 02:40:03
【问题描述】:

是否有与 SendMessage 等效的方法来更改变量而不是调用函数?

例如,我有:

for(int i = 0; i < elements.Count; i++)
{
    elements[i].SendMessage("selectMe", SendMessageOptions.DontRequireReceiver);
}

然后:

public bool selected;
public void selectMe()
{
    selected = true;
}

所以 selectMe() 只是一个额外的步骤。有没有办法切换“选定”本身的值? GetComponent() 是没有问题的,因为变量位于不同的脚本中,具体取决于对象 - 所有这些都确实包含变量“selected”。

简而言之,我正在寻找类似的东西:

elements[i].SendMessage("selected", true, SendMessageOptions.DontRequireReceiver);

(上面不返回错误但也不起作用)

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    这不是一个漂亮的单行,但如果你使用 C# 反射,有一种方法:

    foreach (Component comp in GetComponents<Component>()) {
        // Modify this to filter out candidate variables
        const BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Public | 
                                   BindingFlags.Instance | BindingFlags.Static;
    
        // Change any 'selected' field that is also a bool
        FieldInfo field = comp.GetType().GetField("selected", flags);
        if (field != null  && field.FieldType == typeof(bool)) {
            field.SetValue(true);
        }
    
        // Change any 'selected' property that is also a bool
        PropertyInfo property = comp.GetType().GetProperty("selected", flags);
        if (property != null && property.PropertyType == typeof(bool)) {
            property.SetValue(true);
        }
    }
    

    【讨论】:

    • 我认为它是一种解决方案,但是是的,它并不漂亮,实际上是更多的行。如果没有什么更接近,将接受作为答案。
    • @MrQuestions 我编辑了我的答案以包括类型检查,因此您只需更改也是 bool 类型的“选定”变量。
    【解决方案2】:

    你为什么不能做这样的事情?

    private bool selected;
    
    public void Select(bool select)
    {
        this.selected = select;
    }
    

    然后:

    element.SendMessage("Select", true, SendMessageOptions.DontRequireReceiver);
    

    但如果您想要更短且我认为更好的解决方案,请尝试使用事件

    【讨论】:

    • 这就是我上面写的。我在“selectMe”的行数较多时使用它,但我将其中的大部分导出到“selected”的“get; set”中。现在它实际上是一个行函数,我想摆脱它。
    • 作为旁注,我可能最终会使用它,因为我有“selectMe”和“deselectMe”。竖起大拇指,但最终没有解决问题。
    猜你喜欢
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 1970-01-01
    相关资源
    最近更新 更多