Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Editor script and prefab problem

Discussion in 'Scripting' started by jbecana, Jul 27, 2016.

  1. jbecana

    jbecana

    Joined:
    Feb 14, 2012
    Posts:
    22
    Hi,
    I have a prefab and some scripts on it, one script having a field with a serializeField attribute. I have a couple of objects instantiated from this prefab in the scene. I use an editor script to read/write that field, but when I switch to play mode the field value returns to its prefab value. If I change that field in the inspector works fine (the field is display in a stronger black showing that the prefab value has been overriden). Should I use any special mechanism in my Editor script to tell Unity I want to override that prefab value in my instance? The Editor script works fine with objects not linked to prefabs.
     
  2. MD_Reptile

    MD_Reptile

    Joined:
    Jan 19, 2012
    Posts:
    2,663
    I think when you edit something through an editor script that the editor sometimes doesn't maintain changes unless you save the scene (there's a method you can use for the editor script which will save it for you) so you might try that. Mind sharing the editor script? Might make helping easier...

    Edit: on second thought tho, if the prefab overrides it then that might not work. Hrmmm.
     
    Last edited: Jul 27, 2016
  3. image28

    image28

    Joined:
    Jul 17, 2013
    Posts:
    457
  4. jbecana

    jbecana

    Joined:
    Feb 14, 2012
    Posts:
    22
    Thanks for your answers. I finally found a solution, it might be a bug. While the editor script worked fine changing a regular object, it failed when the object was linked to a prefab. It seems Unity replaces the scene object with the prefab when switching to play mode and only those values overriden through the inspector reatained their values in the scene. In fact, once a field was "manually" overriden through the inspector, changes made through the editor script remain thereafter. Pointing at prefabs, I looked through the docs and found this method:

    Code (CSharp):
    1.         PrefabUtility.RecordPrefabInstancePropertyModifications(m_CS.Area);
    2.  
    Although the documentation says this method is called automatically, I included the line, and voilá, the field text turned bold showing Unity understood that this field had changed from its prefab value. Is it a bug? Anyway I think this should be done automatically or at least mentioned in the Editor docs.

    I also included this line:

    Code (CSharp):
    1.        EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
    2.  
    as I realized that the scene was not marked as dirty after any changes made through the script .