是否有等效的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);
(以上不返回错误,但也不起作用)
解决方法:
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);
}
}