Search code examples
c#unity-game-enginegameobject

Why is transform.parent null in Awake() and Start()?


I'm trying to get a reference to the GameObject that the script is attached to. Per docs transform.parent.gameObject is used for this but transform.parent is null in both Awake() and Start(). What do I need to do to get this working? This is probably a total noob question but Google didn't come up with a working answer so far.

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour
{
    private void Awake()
    {
        var obj = transform.parent;
        Debug.Log(obj);
    }

    private void Start()
    {
        var obj = transform.parent;
        Debug.Log(obj);
    }
}

Solution

  • Transform.parent tells you what the parent of your current transform is. I.E. if GameObjectA is a child of GameObjectB, a script that accesses transform.gameObject in GameObjectB will return GameObjectA

    What you're looking for, in fact, is just gameObject. This implicitly returns the gameObject your script is attached to.

    Create two GameObjects in your scene.
    Call one GameObjectA, and the other GameObjectB.
    Attach this script to GameObjectB and then drag GameObjectB to be under GameObjectA in the hierarchy

    public class ExampleBehaviour : MonoBehaviour {
    
        void Awake () {
            Debug.Log(gameObject.name);        //Prints "GameObjectB" to the console
            Debug.Log(transform.parent.name);  //Prints "GameObjectA" to the console
        }
    
    }