Help with GetComponent

Making it short as possible - I’m too dumb to understand how this works but I think that

Health tmp = gameObject.transform.root.GetComponent<Health>();

should return the Health script in the root object. However, it returns null (probably since thats what the if statement and debug log seems to say. Also, yes I do have the Hleaht script in the root object, and other scripts in the root object can reference it (with just GetComponent). Also if I’m doing things in a dumb way lmk since I tend to do that.

HitboxManager (where the problems at):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HitboxManager : MonoBehaviour {
    public bool isPlayer;

    HealthSystem hpManager;

    // Start is called before the first frame update
    void Start () {
        Health tmp = gameObject.transform.root.GetComponent<Health> ();
        if (tmp != null) {
            hpManager = tmp.hpManager;
            Debug.Log (hpManager.GetHP ());
        } else Debug.Log ("lol tmp didnt work xd ur bad");
    }

    // Update is called once per frame
    void Update () {
        //hpManager.GetHP();
    }

    private void OnTriggerEnter (Collider other) {
        if (isPlayer && other.gameObject.tag == "PlayerHurtbox") { } else if (other.gameObject.tag == "Hurtbox") {
            Debug.Log("lol");
            hpManager.Damage(7);
            Debug.Log (hpManager.GetHP ());
        }
    }
}

Health Script (where hpManager is at, and also is at the root of the object while HitboxManager is at the hitbox 2 down in the societal class system defined by Unity users(i said that since i dont know the word for it shhhhh dont tell)):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Health : MonoBehaviour
{
    public HealthSystem hpManager;
    // Start is called before the first frame update
    void Awake()
    {
        hpManager = new HealthSystem(100);
        Debug.Log(hpManager.GetHP()+" Note: From initial health script.");
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

Hi @dderpym,

can’t really find a flaw in your code, it looks correct. You definitely can access a component of the root gameobject that way. Can you upload your code to googledrive, dropbox, git, etc? I’ll have a look at it, might be the easiest way.

By the way, the societal class system is also called hierarchy :slight_smile:

Seems alright to me. Did you check if the gameobject really has that component?

Otherwise you could also try:

GameObject.Find(“name”).GetComponent< Health>();

Maybe you can figure out the problem with this method.