Search Unity

Instantiate connected prefab inside a hierarchy of GameObjects

Discussion in 'Prefabs' started by eduilnero, Jan 29, 2019.

  1. eduilnero

    eduilnero

    Joined:
    May 9, 2013
    Posts:
    15
    Hi! I am trying to instantiate a prefab through PrefabUtility.InstantiatePrefab( ). After instantiating the object, I want to set it as a child of a certain GameObject in my scene's hierarchy. I can do it in editor manually, but I cannot find a proper way to do it through code.
    In previous versions, I could do something like:

    PrefabUtility.DisconnectPrefabInstance(prefabInstance);
    prefabInstance.transform.SetParent(newParent);
    PrefabUtility.ReconnectToLastPrefab(prefabInstance);

    But these PrefabUtility methods are deprecated from 2018.3

    Any ideas? Thank you very much!
     
  2. eduilnero

    eduilnero

    Joined:
    May 9, 2013
    Posts:
    15
    [Update]
    I found out that if I modify the instance returned by PrefabUtility.InstantiatePrefab() changes are not really set in scene. But if I wait a couple of seconds and I try to do the very same modifications, these are applied. So, as far as I can understand, there should be some callback telling me: "ok, now you can apply modifications to the instance in scene". Any ideas? Thanks again!
     
  3. SteenLund

    SteenLund

    Unity Technologies

    Joined:
    Jan 20, 2011
    Posts:
    639
    @eduilnero

    This should work:
    Code (CSharp):
    1. var instance = PrefabUtility.InstantiatePrefab(myPefab);
    2. instance.GetComponent<Transform>().parent = newParent;
    3. PrefabUtility.RecordPrefabInstancePropertyModifications(instance.GetComponent<Transform>());
    Cheers
     
    eduilnero likes this.
  4. eduilnero

    eduilnero

    Joined:
    May 9, 2013
    Posts:
    15
    Thank you very much, this is exactly what I was looking for.