unity instantiate gameobject as child code example

Example 1: how to instantiate as child unity

Instantiate(obj, pos, rot, parent);

Example 2: unity create a child object

// spawns object
        objToSpawn = new GameObject("Start");

        // add Components
        objToSpawn.AddComponent<Rigidbody>();
        objToSpawn.AddComponent<MeshFilter>();
        objToSpawn.AddComponent<BoxCollider>();
        objToSpawn.AddComponent<MeshRenderer>();

        // sets the obj's parent to the obj that the script is applied to
        objToSpawn.transform.SetParent(this.transform);

Example 3: unity instantiate as child

//SetParent() method
//https://docs.unity3d.com/ScriptReference/Transform.SetParent.html
//or something like this 
 var myNewSmoke = Instantiate (poisonSmoke, Vector3(transform.position.x,transform.position.y, transform.position.z) , Quaternion.identity);
   myNewSmoke.transform.parent = gameObject.transform;

Example 4: instantiate gameobject as child

// 1. create game object
// 2. set its transform.parent property
GameObject child = GameObject.Instantiate(MyPrefab);
child.transform.parent = this.gameObject.transform; //or whatever gameobj will be its parent