c# - 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# 反射,有一种方法:
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);
}
}
推荐阅读
- python - 使用os重命名目录中的多个文件返回错误
- google-sheets - ArrayFormula 仅适用于 Indirect() 的第一行
- java - 将 kotlin 转换为 java 以传递给 Firestore
- java - 启用排序时的 JavaFX Tableview 标题颜色
- python-2.7 - TensorFlow 中转置卷积的自定义填充(浮点类型)
- java - NoSuchMethodError - java.lang.NoSuchMethodError : javax/ws/rs/core/Application.getProperties()Ljava/util/Map
- firebase - Vue.js:带有 vue-moment 的控制台警告,带有来自身份验证的 firebase 日期 - 日期已更新
- ldap - 从 UnboundId LDAP 搜索结果中删除用户的密码
- c++ - 删除带有向量的类
在 C++ 中 - phpunit - 如何使用 ddev 运行 TYPO3 功能测试?