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

Programmatically apply additions to prefabs hierarchy after addition via editor script

Discussion in 'Prefabs' started by Rs, Aug 27, 2021.

  1. Rs

    Rs

    Joined:
    Aug 14, 2012
    Posts:
    74
    I'm having a hard time unraveling Unity's complexity with prefabs management and the PrefabUtility.
    I made an editor script that adds a few components to the active scene.
    I process all game objects that were affected by doing (simplifying a bit)

    Code (CSharp):
    1. if (PrefabUtility.IsPartOfAnyPrefab(go))
    2. {
    3.     GameObject prefabContainer = PrefabUtility.GetOutermostPrefabInstanceRoot(go);
    4.     EditorUtility.SetDirty(prefabContainer);
    5.     PrefabUtility.ApplyPrefabInstance(prefabContainer, InteractionMode.AutomatedAction);
    6. }
    I would have thought this was enough but it is not applying correctly to the prefabs I want (they always remain as overrides) and considering some scenes have nested prefabs, prefab variants, prefab variants nested into prefabs, and so on, I kind of figured this would happen so what I really need to know is
    How do I collect all the prefabs (variants, roots, prefab containers of prefab containers...) that need an "apply" after adding a component to a game object that's in their (descendant) hierarchy?
    Thanks all!
     
  2. pietrodenicola

    pietrodenicola

    Unity Technologies

    Joined:
    Dec 8, 2020
    Posts:
    43
    Maybe you are missing some GameObject in your list. How do you get the list of all GameObjects currently in scene? And yet, consider that you might have some Prefab that is not instantiated in your scene.