- Home /
How can you use Reflection to create an object editor window
I created an editor window control in Unity to easily edit the PlayerInfo object in my game without changing code. You can edit the object in the window and save it out a serialized file that the game can read. I was originally doing this manually by adding each field to the control when I edited the PlayerInfo object. I would like to use Reflection to have this done automatically when the PlayerInfo object changes. However, my attempt to do this causes Unity to crash (not the script or my game, Unity itself crashes). This is what I have been trying to do...
Type type = typeof(PlayerInfo);
var fields = type.GetFields();
foreach(FieldInfo field in fields)
{
object temp = field.GetValue(playerInfo);
if(temp is string)
{
field.SetValue(EditorGUILayout.TextField(field.Name + ": ", (string)temp), (string)temp);
}
else if(temp is int)
{
field.SetValue(EditorGUILayout.IntSlider(field.Name + ": ", (int)temp, -1, 100),(int)temp);
}
else if(temp is float)
{
field.SetValue(EditorGUILayout.Slider(field.Name + ": ", (float)temp, 0f, 200f), (float)temp);
}
}
Answer by Bunny83 · Feb 10, 2013 at 06:36 AM
Just take a look at the SetValue function. It takes two parameters.
The first one is the object instance of which you want to set the field. If the field is a static field you would pass null. However in your case it's an instance field so you have to pass your object reference.
The second parameter is the actual value you want to assign to the field. Here you should pass the "changed value". Since the sliders / TextField will return the changed value, this is what you want to pass
field.SetValue(playerInfo ,EditorGUILayout.TextField(field.Name + ": ", (string)temp));
What you've done is you tried to set the field on the boxed string / int / float which is returned by the TextField / slider function. Of course they are not actual reference types and are not of type PlayerInfo.
Last thing is: There's no difference between Unity, your game and your script. They all run in the same Mono Environment inside the editor. If any part crashes the whole system will crash.
This line will make the editor and your game crash as well:
while(true){ }