Issue with GetComponent

I’m pulling a variable for some calculations in the script below, from another script on another object. Now normally this works just fine, if the variable I call is in a script on the same object, but it doesn’t seem to work when on another object and I’m not sure what I’m missing.

EnergyandLife EnergyandLifeScript = GetComponent<EnergyandLife>() as EnergyandLife;
energycurrent = EnergyandLifeScript.energy;

The only unique aspects of this script is that this script is on the camera object and it is using ONGUI, though the above is in udpate(). The energycurrent is not being updated from the EnergyandLife script.

Any help would be appriciated, its been very frustrating! In C# by the way.

You need a reference to the game object, either find it by name or tag, then use GetComponent.

Also, you do not need to use “as EnergyandLife” after use of GetComponent(), you already specified the type.

GetComponent in this case is looking for a script on the current object called EnergyandLife, if the current code in your post is attached to GameObject type, but doesn’t have EnergyandLife, it isn’t going to find it.