- Home /
Using a custom editor script with a prefab instance causes my variables to reset on Play
I wrote an editor script for a Monobehaviour script of mine. Everything was going great until I put the GameObject containing the Monobehaviour into a prefab. At that point, anytime I tweak a variable in the prefab instance, it is automatically reset to the same value as in the prefab as soon as I hit Play.
Before Play:
After Play:
**Note that 5 is the default value in the prefab.*
Removing the Monobehaviour script from the instance and putting it back on fixes the problem. Replacing my Editor code by DrawDefaultInspector also fixes it.
Is there any way to fix it other than performing this ritual every time?
Answer by Smike · Apr 14, 2014 at 07:05 PM
Okay, I solved the problem! I should have communicated with my variable through a SerializedProperty instead of manipulating it directly. More info here:
http://docs.unity3d.com/Documentation/ScriptReference/Editor.html
Quote from the page: "it's advantageous to use the SerializedObject and SerializedProperty system to edit them, since this automatically handles multi-object editing, undo, and prefab overrides."
So I guess using SerializedObject and SerializedProperty is generally better! It seems like they're necessary to actually serialize my changes. I'll use them from now on :)
Answer by corris_unity · Nov 11, 2020 at 01:26 AM
Another solution is to call PrefabUtility.RecordPrefabInstancePropertyModifications after making your changes. This basically handles applying your changes as overrides, so that Unity knows not to revert the values in play mode.
I used it because I was in a situation where SerializedProperty was too limited for the changes I needed to make.
Answer by BHS · Apr 13, 2014 at 07:37 AM
If I'm correct this is because Unity will always get the value from the prefab regardless of the input made after. You must break your prefab connection in order to retrieve the value from it. If it's found at start you need to instantiate it at the start of the scene and get the value then.
Thanks, that does work as a temporary fix for the problem. I'll do that for now.
However, that is not how Unity usually is supposed to work, since if I do the exact same thing on an object that doesn't have a custom editor on, pressing Play doesn't revert it's values to the prefab's values.
Your answer
Follow this Question
Related Questions
Edit an object in isolation quickly, as in the new Prefab Mode 0 Answers
Automatically increment an integer field in a bunch of prefab gameobjects in the unity editor. 0 Answers
How to save sprite color change on custom inspector ? 0 Answers
Editing prefab fields from custom editor that are not automatically serialized 0 Answers
Serialization with custom editor, prefab not saving (again) 1 Answer