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

How to add nested prefab from a custom inspector?

Discussion in 'Prefabs' started by PNordlund, Feb 20, 2019.

  1. PNordlund

    PNordlund

    Joined:
    Nov 20, 2013
    Posts:
    48
    Here's the setup. I have a prefab that I open to "prefab mode" in editor, let's call the root prefab as "Window":

    Window (Existing prefab)
    --A (Child, not a prefab)
    -- B (New nested prefab that I instantiate from a script)

    I have a script in A which I can use to instantiate B from a prefab. This works, but when I exit prefab mode, the instantiated prefab (B) is not saved as part of the "Window" prefab. Here's the code:

    GameObject A = ...;
    GameObject go = PrefabUtility.InstantiatePrefab(myPrefabB) as GameObject;
    go.transform.SetParent(A.transform, false);

    I'm obviously the call to a PrefabUtility method that adds the instantiated prefab B to be part of the Window prefab. Any clues?

    This all works if I just drag B into its place in the editor, but that's not what I want to achieve.
     
    Last edited: Feb 20, 2019
  2. SteenLund

    SteenLund

    Unity Technologies

    Joined:
    Jan 20, 2011
    Posts:
    639
    Hi,

    There reason this is not saved when existing Prefab Mode, is because Prefab Mode scene is not marked dirty.

    You can do this by implementing Undo or simply mark the scene dirty
    EditorSceneManager.MarkSceneDirty(A.scene)
     
    wesleythomas360 likes this.
  3. PNordlund

    PNordlund

    Joined:
    Nov 20, 2013
    Posts:
    48
    Thanks! That's it. It's a bit sneaky though, because you are editing a prefab, not scene... :)