Search Unity

[solved] How to properly nest a prefab via script?

Discussion in 'Prefabs' started by palex-nx, Jul 23, 2018.

  1. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    Hello community!

    I am trying to create a custom scripted importer for assets of type widely used inside our company to seamlessly integrate those assets into unity workflow and throw away outdated toolset. This is impossible without this new shiny nested prefabs unity feature. I've downloaded a preview build, but can't find the way to nest a prefab within another prefab via editor script. I would like to do something like this:

    Code (CSharp):
    1. var parent = PrefabUtility.CreatePrefab(parentPath, parentObject);
    2. var child = PrefabUtility.CreatePrefab(childPath, childObject);
    3.  
    4. PrefabUtility.NestThePrefab(parent, child);
    Is this currently possible? Thank you!
     
    Last edited: Jul 23, 2018
  2. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    I've found a solution and it works like a charm. You need to instantiate both prefabs, parent them properly with transform.SetParent, and then you just
    Code (CSharp):
    1. PrefabUtility.ApplyPrefabInstance(parentInstance, InteractionMode.AutomatedAction);
    Do not forget to destroy the parent instance afterwards to cleanup the current scene.
     
    tosiabunio likes this.