I’m trying to access a variable in a script which is located on a child on another gameobject. I’ve looked at both Transform.Find and GetcomponentsinChildren but I can’t seem to get it to work. In the example below I’m trying to acces the float “bossHealth” which is located on a child of the Gameobject Boss (Clone). I first check whether the object exists or not before trying to set the bossHealth float to the local bossHealthGet float.

public Component bossScript;
private float bossHealthGet;

    
    void OnGUI(){

    		if(GameObject.Find("Boss(Clone)") != null){
    			bossScript = GetComponentsInChildren<Boss_FloatingBehaviour>();
    			bossHealthGet = bossScript.bossHealth;}
   
    }

The script shouldn’t even compile as Unity’s type Component doesn’t have any clue about the methods and variables which are declared in your class. Your bossScript variable needs to be of type Boss_FloatingBehaviour.

Also, please don’t put that into the OnGUI function. It’s called way too often, usually even more often than Update and that’s already a place where frequent calls of GameObject.Find and similar methods should be avoided.

Find the object once (in Start for example) or make a public variable with the type being GameObject or Boss_FloatingBehaviour and assign it via the inspector. Updating the variable can be done in Update or with some other mechanism.

The problem is when you call GetComponentsInChildren you’re getting the Components of the GameObject the current script is attached to rather than the boss object you want to get them (or rather it) from. There is also a couple things about your code structure that might slow down your game due to performance reasons, the biggest being the cost of GameObject.Find, especially having it run every frame in OnGui. If you absolutely need to run it in realtime (as in your boss is instantiated sometime after Start) then try using a tag to look up the GameObject as it’s a lot faster. Also, while bossScript is a Component it’s type is the name of the class, Boss_FloatingBehaviour. If you were to use the Component type in the variable like that you would first have to cast it to it’s type before using it.

To show what the code might look like with some fixes:

private GameObject boss;
private Boss_FloatingBehaviour bossScript;
private float bossHealthGet;

void OnGui()
{
    //Having GameObject.FindObjectWithTag("Boss") would be faster here
    boss = GameObject.Find("Boss(Clone)");
    if (boss != null)
    {
        bossScript = boss.GetComponentInChildren<Boss_FloatingBehaviour>();
        bossHealthGet = bossScript.bossHealth;
    }
}