Unity-SendMessage,但使用变量而不是函数/方法

时间:2018-10-03 17:55:25

标签: c# unity3d

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

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

2 个答案:

答案 0 :(得分:2)

这不是一个好方法,但是如果您使用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);
    }
}

答案 1 :(得分:1)

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

private bool selected;

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

然后:

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

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