Day 12 — Getting a reference to a different script in Unity
Hey and welcome!
Let’s paint the scene here, in our Player script we have the following method in place to handle what happens when the player is damaged:
public void Damage()
_playerLives -= 1;
if (_playerLives < 1)
Which works all when a good but the problem here is that we’re wanting to run this method in our Enemy script where we’re checking for the collision.
Unfortunately we can’t just initialise the method in our Enemy script by typing out Damage() because there isn’t a previous reference to it in our Enemy script at all so the code has no idea where it’s coming from. So what we’re going to do here is use something called GetComponent in order to access the Player component/script on the Player object that you can see within the inspector.
It’s easy enough to do if we add in the following code into our OnTriggerEnter() method inside the if statement that checks if the tag is “Player”:
First there’s other.transform which if you remember from before that other is storing our Player object so all that’s happening here is that we’re accessing the root of the Player object. While we’re in the root we can use GetComponent<Player>() to get the Player script/component as seen in the inspector here:
With that we have a reference to our player script meaning we can run any methods inside it which in this case we’re initialising the damage method with .Damage() and that’s some pretty cool stuff when you get your head round it.
Now with that all working there’s one last thing I need to mention to you and that’s null checking. Let’s say that we forgot to attach the Player script to our Player, if the enemy was to collide with our Player object our game will crash and we get an error looking like this NullReferenceException: Object reference not set to an instance of an object which tells us that it’s trying to access a component (the Player component) that doesn’t exist.
What we want though is for our game to keep running even with this so we’ll need to do some null checking:
Player player = other.transform.GetComponent<Player>();
if (player != null)
Two main things to take note of is that we’re storing the Player component within a local player variable we’re defining which we then use later to initialise our Damage() method. The other thing is that we’re checking if player (which holds our Player component) is null and if it is then the Damage() method is not called. That means that now when an enemy collides with our player the game will carry on without errors, the only thing is different is that the player doesn’t lose a life when collided with which is an easy way to tell that the Damage() method is not getting called.
With everything working though you should have something looking like the above here where our Player object is destroyed when their lives reach zero after losing 1 life per enemy it collides with.