Is there an equivalent of SendMessage to change variable instead of calling a function?
For example, I have:
for(int i = 0; i < elements.Count; i++)
{
elements[i].SendMessage("selectMe", SendMessageOptions.DontRequireReceiver);
}
and then:
public bool selected;
public void selectMe()
{
selected = true;
}
so selectMe() is just an additional step. Is there a way to switch value of "selected" itself? GetComponent<>() is out of question since variable is located in different scripts, depending on object - all of which do indeed contain variable "selected".
In short, I'm looking for something like:
elements[i].SendMessage("selected", true, SendMessageOptions.DontRequireReceiver);
(above doesn't return an error but it doesn't work either)
It's not a pretty one-liner, but there is a way if you use C# Reflection:
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With