-1

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);

HitesH
  • 21
  • 1
  • 3
  • 1
    `Instantiate(EnemyPrefab[Random.Range(0, EnemyPrefab.Length)], SpwanPos, Quaternion.identity, selectedObject.transform);` ...? – derHugo Jan 05 '22 at 10:15

1 Answers1

0

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";
    }

}
Saif
  • 178
  • 10