Home > Mobile >  How to set an at runtime instantiated prefab as a parent of another runtime prefab?
How to set an at runtime instantiated prefab as a parent of another runtime prefab?

Time:11-30

we are currently facing a problem in Unity where we are trying to develop a flexible UI where the "MainCanvas" consists of runtime prefabs.

We can already instantiate runtime prefabs set as parent of a GameObject existing in the scene. But we want the parent to be an instantiated prefab as well.

Is it posible to make this somehow work or are there any other alternatives that we should be looking into.

Thanks before hand to anyone reading this !

We already tried to implement the given example but it always returned an error in the console.

Sadly we already changed a bit in the program so we can't really recreate the error message but if anyone is intressted we can revert and take a screenshot.

Thanks to anyone reading this again and we hope to find a solution :)

CodePudding user response:

  1. Store the reference of the parent instance
  2. Use Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent) method to instantiate the sceond prefab instance below the parent instance

Here's my test code, works fine :

public class PrefabParentTest : MonoBehaviour
{
    [SerializeField] private GameObject _prefab1;
    [SerializeField] private GameObject _prefab2;
    void Start()
    {
        var instance1 = Instantiate(_prefab1, Vector3.zero, Quaternion.identity);
        var instance2 = Instantiate(_prefab2, Vector3.zero, Quaternion.identity, instance1.transform);
    }
}

Runtime

Or, you can use Transform.SetParent (not recommended as the first one) to achieve the same goal:

 void Start()
 {
        var instance1 = Instantiate(_prefab1, Vector3.zero, Quaternion.identity);
        var instance2 = Instantiate(_prefab2, Vector3.zero, Quaternion.identity);
        instance2.transform.SetParent(instance1.transform);
 }

Refs:

  • Related