Okay so I made a class to take an input script and a property name. It finds the property and then displays it when Display() is called [ The display method is overridden by a child class ]. However, there is one problem that I have with it and that is how do I cache what FieldInfo.GetValue() returns? It would be preferable to have a pointer or something to reuse once the variable containing what I need is found since reflection is costly.
public class PropertyDisplayer : MonoBehaviour
{
public string PropertyName;
public Object TargetObject;
public object _TargetObject;
public FieldInfo Property;
void Start()
{
_TargetObject = TargetObject;
if (!PropertyName.Contains("."))
{
Property = _TargetObject.GetType().GetField(PropertyName);
}
else
{
string[] split = PropertyName.Split('.');
Property = _TargetObject.GetType().GetField(split[0]);
for (int i = 1; i != split.Length; i++)
{
_TargetObject = Property.GetValue(_TargetObject);
Property = Property.FieldType.GetField(split[i]);
}
}
}
public virtual void Display()
{
}
}
Use the dynamitey library, it will cache all reflection calls transparently for you and make them near normal call speed. More info here: https://github.com/ekonbenefits/dynamitey
You can store the results of the FieldInfo.GetValue() call in a new member field that is of type "object". (This IS, effectively, a pointer)
Then, in your Display() override, simply cast this member to the appropriate class, in order to access its members.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.