Search Unity

  1. Get the latest news, tutorials and offers directly to your inbox with our newsletters. Sign up now.
    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:
    600
    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)
     
  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... :)
     
unityunity