Can't change public variables on a script attached to a gameobject. Values are restored upon play

13,168

You need to call EditorUtility.SetDirty (tb); after all changes are done, see EditorUtility.SetDirty for more information on this.

In case you need to change the prefab itself, have a look at PrefabUtility

Share:
13,168
ymerkryds
Author by

ymerkryds

Updated on June 16, 2022

Comments

  • ymerkryds
    ymerkryds almost 2 years

    Here is my first question. Haven't been able to find anything on the topic.

    I want to create an editor script that changes a number of public bools in a script that is attached to a GameObject.

    I have this script attached to a GameObject. The GameObject is a prefab:

    using UnityEngine;
    using System.Collections;
    
    public class ScriptWithPublicBools : MonoBehaviour {
    
        public bool b1;
        public bool b2;
    }
    

    And here is my editor script:

    using UnityEngine;
    using System.Collections;
    using UnityEditor;
    
    public class EditorHelper : ScriptableObject
    {
        [MenuItem("Trace/Trace")]
        public static void trace()
        {
            foreach (GameObject g in Selection.gameObjects)
            {
                ScriptWithPublicBools tb = g.GetComponent<ScriptWithPublicBools>();
    
                if (tb)
                {
                    tb.b1 = false;
                    tb.b2 = true;
                }
            }
        }
    }
    

    The scripts are working fine and the bools on the gameobject is set correctly in the editor. But when I press the PLAY button the values of the two bool switches back the values they were before the script was applied.

    It does not matter what the values of the prefab is, the values are just restored to the values before applying the editor script.

    Am I doing something wrong or is it a bug?

    If I apply the editor script, save the scene as a new scene, and open the newly created scene the values are also wrong.

    BUT, if the GameObject is not a prefab all works perfectly, and the values keep their values given by the editor script, even after initiating play mode.

    So the problem is only present when using prefabs.