首页 > 解决方案 > Unity - SendMessage,但用于变量而不是函数/方法

问题描述

是否有等效的 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

解决方案


这不是一个漂亮的单行,但如果你使用 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);
    }
}

推荐阅读