set parent unity code example

Example 1: setparent unity

using UnityEngine;public class ExampleClass : MonoBehaviour
{
    public GameObject child;    public Transform parent;    //Invoked when a button is clicked.
    public void Example(Transform newParent)
    {
        // Sets "newParent" as the new parent of the child GameObject.
        child.transform.SetParent(newParent);        // Same as above, except worldPositionStays set to false
        // makes the child keep its local orientation rather than
        // its global orientation.
        child.transform.SetParent(newParent, false);        // Setting the parent to ‘null’ unparents the GameObject
        // and turns child into a top-level object in the hierarchy
        child.transform.SetParent(null);
    }
}

Example 2: set parent of gameobject unity

child.transform.SetParent(newParent);

Example 3: parent unity

public gameobject player
public gameobject Newparent
player.transform.parent = newParent.transform;

Example 4: unity set parent canvas

[MenuItem("GameObject/UI/Switch")]
static void Switch()
{
    //Create new GameObject
    GameObject go = new GameObject("switch");


    //Find Canvas in the Scene
    Canvas canvas = (Canvas)GameObject.FindObjectOfType(typeof(Canvas));

    //Get Canvas GameObject
    GameObject canvasGameObject = canvas.gameObject;

    //Make the new GameObject child of the Canvas
    go.transform.parent = canvasGameObject.transform;
    go.transform.localPosition = Vector3.zero;

    //Change the new GameObject Layer to UI
    go.layer = 5; //Or go.layer = canvasGameObject.layer;

    //Add Rect Transform to it
    go.AddComponent<RectTransform>();
}