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.
*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?
Okay, I solved the problem! I should have communicated with my variable through a SerializedProperty instead of manipulating it directly. More info here:
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
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.
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.