Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved Changing Prefabs per code doesn't create overrides

Discussion in 'Prefabs' started by Noblauch, Jul 14, 2020.

  1. Noblauch

    Noblauch

    Joined:
    May 23, 2017
    Posts:
    270
    I'm trying to edit my scenes and prefabs on save. The scene works great, as long as I don't try to edit prefabs.
    I wrote a post processor to go over the scene and change the things I need. For simplicity I give you a very basic example to reproduce:

    Code (CSharp):
    1. [InitializeOnLoad]
    2. public static class SceneSavePostprocessor
    3. {
    4.     static SceneSavePostprocessor()
    5.     {
    6.         EditorSceneManager.sceneSaving += SceneSaving;
    7.     }
    8.  
    9.     private static void SceneSaving(Scene scene, string path)
    10.     {
    11.         GameObject.Find("TEST").GetComponent<Image>().color = Color.red;
    12.     }
    13. }
    Add a UI Image component to the scene, name its game object "TEST" and make it a prefab.
    create the script above, hit save on your scene, observe how the Image color turns red, the post processor is working.
    Reopen the scene and observe, that the changes were not saved. You can also see that there is no indicator on the prefab that normally appear when you add overrides manually.

    If you try the same without making the object a prefab it also works as expected.
     
  2. Noblauch

    Noblauch

    Joined:
    May 23, 2017
    Posts:
    270
    Okay, it seems like you have to set the edited components dirty in the case of prefabs:
    EditorUtility.SetDirty(myComponent);

    This fixed the overrides not getting set.
     
    cjjeffery and SimonKeating like this.
  3. Mads-Nyholm

    Mads-Nyholm

    Unity Technologies

    Joined:
    Aug 19, 2013
    Posts:
    217