Search code examples
c#unity-game-enginespawn

how do instantiate GameObject as child of a selected object


I want to instantiate a game object as a child of the selected object. need help right now I'm using this Instantiate(EnemyPrefab[Random.Range(0, EnemyPrefab.Length)], SpwanPos, Quaternion.identity);


Solution

  • There are various ways to instantiate an object (Source: InstantiateChildObject)

    public static Object Instantiate(Object original);
    
    public static Object Instantiate(Object original, Transform parent);
    
    public static Object Instantiate(Object original, Transform parent, bool instantiateInWorldSpace);
    
    public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);
    
    public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);
    

    If you would like to instantiate the prefab as a child of GameObject in world space, then:

    GameObject childGameObject = Instantiate(yourPrefab, parentOfObject, true);
    childGameObject.name = "Enemy01";
    

    Do not forget to reset the transforms after it is parented (Or set your own transform)

    A list of functions for all types of instantiating as child:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class InstantiateAsChild : MonoBehaviour
    {
        public GameObject prefab;
        public Transform parent;
        public Vector2 position;
        public Quaternion rotation;
    
        public void childInstantiate()
        {
            GameObject childGameObject = Instantiate(prefab);
            childGameObject.name = "Instantiate";
        }
    
        public void childInstantiateAsChild()
        {
            GameObject childGameObject = Instantiate(prefab, parent);
            childGameObject.name = "InstantiateChild";
    
        }
    
        public void childInstantiateAsChildWorldSpace()
        {
            GameObject childGameObject = Instantiate(prefab, parent, true);
            childGameObject.name = "InstantiateWorldSpace";
        }
    
        public void childInstantiateWithPositionRotation()
        {
            GameObject childGameObject = Instantiate(prefab, position, rotation);
            childGameObject.name = "InstantiatePosAndRot";
        }
        public void childInstantiateAsChildWithPositionRotation()
        {
            GameObject childGameObject = Instantiate(prefab, position, rotation ,parent);
            childGameObject.name = "InstantiateChildPosAndRot";
        }
    
    }