- Home /
Property values changed by custom editor are reset when start playing
I have a scripts like this below. Problem is when I assign value to clampedValue in inspector and click play button all private fields are reset to their default value. So if I assign 60 to clampedValue, in play mode it becomes 50 again. How can I save values of properties (of private fields)?
(Sorry for my English)
public class MyClass : MonoBehaviour
{
public float clampedValue
{
get { return _clampedValue; }
set { _clampedValue = Mathf.Clamp(value, 0, Mathf.Infinity); }
}
private float _clampedValue = 50f;
}
[CustomEditor(typeof(MyClass))]
public class MyClassEditor : Editor
{
public override void OnInspectorGUI()
{
MyClass obj = (MyClass)target;
obj.clampedValue = EditorGUILayout.FloatField("Clamped Value", obj.clampedValue);
}
}
A different approach is to use serializedObject
and access your variable through SerializedProperty
variables, and then at the end call serializedObject.Apply$$anonymous$$odifiedProperties ();
to "save" changes to the object you are editing.
There is a good example how to do this here, in the scripting reference.
That's going into Property Drawers and Custom Inspectors. That's unnecessary in this case.
Answer by Sabre-Runner · Jul 22, 2018 at 06:39 PM
Maybe it's because you're handling a property and the actual field is not an inspector field?
In inspector debug mode I see private field is changed after changing property in inspector but when I click play button, $$anonymous$$onoBehaviour constructor is called and it resets the value of the field. How can i prevent it?
I tested something right now. I made my field public and changed the value of property. When I clicked play button it didn't change. So if saying 'inspector field' you mean public field then you're right but how can I set private fields as inspector fields.
An inspector field is any field that is exposed to the Inspector. If it is, the Inspector setting overrides the class construction. If not, then it doesn't.
You have two options to set an inspector field: mark it public (but than every outside class can access it) or use the [SerializeField] attribute on a private field.
Answer by sfilo · Oct 12, 2020 at 03:46 PM
I had a similar problem. It turned out I was editing a prefab and had to set EditorUtility.SetDirty(target); to indicate to the editor that the prefab instance has changed properties.
I have been struggling on this for hours! Thank you so much!
Stuggled for weeks because some important variable was resetting. This single line of code fixed it