# Public variable changed in script isn't stored in playmode

I have a public variable float x in script Foo.cs. I have a Bar.cs script with a function like this:

bar() {
Foo foo = FindObjectOfType<Foo>();
foo.x = 1f;
}


And a custom editor which calls bar() when a button is pressed. All of that works fine in the editor, my float x is changed to 1, but when I enter playmode the value changes itself. If I change it manually in the inspector it works fine too. So for example:

• I set x manually in the inspector to 10.
• I enter play mode, x is still 10.
• I exit playmode and call the bar() function.
• x has changed to 1 in the inspector.
• After hitting "Play" x changes back to 10.

How can I fix this?

## 1 Answer

Welcome to the rabbit hole of Unity Editor scripting. Whenever you change serialized values, you need to tell unity. The object you are changing at editor time is just a copy of the serialized one. If your editor is acting on the copy object (i.e. you're using the "target" property) then you need to call Undo.RecordObject. Unity recommends working on the SerializedObject. SerializedObject is NOT a representation of your target object. it IS a representation of serialized data stored by the editor that is used to build your target object. This can be complicated to wrap your head around at first. I've also found many unity editor API references to be wrong, or misleading. I can't list all the pitfalls in one answer, so just heed my warning.

• Not part of my answer, because I don't think using assets is a good "answer". But take a look at OdinInspector on the asset store. It makes a lot of this stuff far easier to work with. It also provides a bunch of editor functionality that is very very useful. If you can afford it, i'd recommend it. – gjh33 Apr 9 '19 at 16:36