I am working an a battle sequence scene for an RPG and so far I have a script for the player and the enemy health, and am trying to call the enemy health variable from the player script.
My question is why doesn’t this script work without having to attach the game object to this script?
The script, left exactly the same way without the bold parts, returns an error like this
NullReferenceException: Object reference not set to an instance of an object
Player.Update () (at Assets/Levels/2 - Instance/Player.cs:27)
The reason I am worried about this right now is because if later on if I have 500 enemies, I don’t want to have to attach each of their gameObjects to my main player to subtract their health.
I assume the bold part in Awake would be ‘enemysprite:GetComponent…’ instead of just ‘enemy’.
Any component in your scene must belong to a GameObject, and GetComponent tries to get an instance from a GameObject.
If you do not specify a GameObject, such as
GetComponent<TComponent>()
that will end up being the same as this.GetComponent<TComponent>() where ‘this’ refers to the behaviour itself and is the same as
gameObject.GetComponent<TComponent>()
// or
this.gameObject.GetComponent<TComponent>()
You’ll always get the same result, as the GameObject in this case will always be the one that your script is being attached to.
But your Enemy script is on a different GameObject, so you need to tell the script on which one you want to call the GetComponent method.
You do not necessarily need to link and cache them at startup. There are other techniques that can be used to get a reference to the enemies once you need them. But that depends on your specific needs.