Unity how to get parent object

Parent in Unity: The Full Guide

The concept of parent in Unity enables the hierarchical organization of game objects in our scene.

Let’s take a look at the different functions available for modifying a parent.

Table of Contents

Get the Parent Object

To retrieve the parent of an object, access its “transform” component and then call the “parent” property:

Unity parent

using UnityEngine;

public class Parent : MonoBehaviour
{
    public GameObject gameObjectRef;

    private void Start()
    {
        var root = gameObjectRef.transform.parent;
    }
}
    

Get the Parent Root

The root is the topmost object in the hierarchy.

To retrieve the root of an object, call the “root” property:

Unity root

using UnityEngine;

public class Root : MonoBehaviour
{
    public GameObject gameObjectRef;

    private void Start()
    {
        var root = gameObjectRef.transform.root;
    }
}
    

Set Parent

To assign a parent to an object, use the “SetParent” property.

If you want to assign a parent without modifying the scale, position, and rotation of your object, you can add “true” as the second parameter:

using UnityEngine;

public class ParentMonoBehaviour : MonoBehaviour
{
    [SerializeField]
    private Transform _transform;

    private void ChangeParent()
    {
        transform.SetParent(_transform);

        // child stays at world position
        transform.SetParent(_transform, true);
    }
}
    

Remove Parent

To remove the parent of an object and make it the root, use the “SetParent” function with “null” as the parameter:

using UnityEngine;

public class ParentMonoBehaviour : MonoBehaviour
{
    private void RemoveParent()
    {
        transform.SetParent(null);
        // or
        transform.parent = null;
    }
}
    

Key Points

  • Parenting/hierarchy manipulations in Unity are always performed using the transform component.
  • Use the “root” property to retrieve the first element in the hierarchy.
  • Use the “SetParent” method to associate or remove a parent.
  • Use the “parent” property to retrieve a parent.

Leave a Reply

Your email address will not be published. Required fields are marked *