Helping scripts communicate in Unity
My goal is going to be looking at how scripts communicate in Unity, as well as set up a health system for the player, including death. Before anything else though, I’ll talk a bit more about the tag system I sort of skipped over yesterday.
It’s another simple but powerful tool that Unity offers, giving you the ability to CompareTag in order to search for groups of things that you define.
Now, I’m going to look at how to add lives/health to the player. By default, Unity doesn’t know what lives are, so first I need to define it and determine how many my Player has. Of course, I’m going to do this with a private integer: private int _lives = 3;. This might be a surprise, because private means that other objects can’t access it, but I don’t want to let other scripts or programs modify that directly, I still want the Player to be in control of its own health, and take it down itself.
So I’m going to create a custom method below my FireLaser handler, and make it public. public void Damage(), adding the public in front allows enemies and power-ups to access this section of the Player script.
Now I need to move back to the Enemy.cs script in order to actually interact with that public Damage method.
But I can’t just use other.player to access the script, I can only directly access the transform of another object. Instead, I have to access the object, then tell Unity what I’m looking for with GetComponent:
However, I want to do what’s called a null check, to do my best to avoid errors and ensure that the component I’m checking for actually exists. I do this by storing the player into a variable and run it against != (not equal to) null.
Now let’s check to make sure the Player dies correctly by testing it out! I added a few more enemies since my spawn management system isn’t yet in place.
As you can see, Player dies after three hits, perfect. Just going to handle up code clean up now.
Next I’ll be setting up the spawn manager, thanks for reading!