- Home /
MonoBehaviour Properties not saving their values from Editor
When I change a value, it stays, but as soon as I hit play it resets to 0/default.
public class SomeComponent : MonoBehaviour
{
public int SomeValue { get; set; }
}
Custom Editor:
[CustomEditor(typeof(SomeComponent))] public class SomeComponentEditor : Editor { private SomeComponent Target { get { return (SomeComponent)this.target; } }
public override void OnInspectorGUI()
{
EditorGUIUtility.LookLikeInspector();
EditorGUILayout.BeginVertical();
Target.SomeValue = EditorGUILayout.IntField("Some Value", Target.SomeValue);
EditorGUILayout.EndVertical();
}
}
Answer by George · Oct 03, 2010 at 07:59 AM
Yes this is all a ruse, but the purpose was to note it down here for others.
What you have to do is not use auto-properties. You have to apply the [SerializeField] attribute to your backing field, so the following, modified version of SomeComponent works:
public class SomeComponent : MonoBehaviour { [SerializeField] private int _someValue;
public int SomeValue
{
get { return _someValue; }
set
{
if (_someValue == value) return;
_someValue = value;
}
}
}
It's a shame, because auto-properties are so neat. Unity should definitely add [SerializeProperty], knowing that the compiler should make its own backing field.
You got me there! You naughty prankster you :) Yup, it's a good piece of information. +1 just for kicks.
See, now this makes my day just a little rougher around the edges...I do NOT have to do this for public variables, they work just fine out of the box. On the other had I have this EXACT problem when using public static variables. You gave me a glimmer of hope for a moment there though, really thought this would fix my problem, but it doesn't seem to affect it. if you feel like it you can look at my question Static variables assigned in the inspector
Answer by chirhotec · Feb 17, 2011 at 03:07 PM
I'm having this problem, but I don't understand how this fixes it. I've been using the custom ExposeProperty attribute provided here. I could have sworn it worked perfectly in the past, but at some point it broke and I can't figure out how to fix it.
The problem with the proposed solution is that when you made changes to _someValue from the editor, it doesn't call the setter, and so you never run the additional processing your setter might do.
$$anonymous$$aking changes to _someValue ins$$anonymous$$d of using SomeValue doesn't call the setter at runtime either. This is not specific to the Unity editor.