Life, death and get components
Now with any arcade style game, 1 key feature we will need to have in place is a life mechanism. Otherwise, if we were back in our favorite arcade playing games, we wouldn’t have a need for all those quarters.
First thing we have to do is go over to our player script and get a lives component made up.
Once we have our private Lives set up, we now have to make a system so that when we take some damage, we lose a life.
As we can see above, we have a couple different methods we can use to tell Unity to subtract a life, and in the end, whichever you choose is perfectly fine. Now, we will want to write out some code so that Unity knows that once our lives hits 0, we are destroyed.
Now for something a little more complex to work with, script communication. This is a method that is a little more complicated for some newer uses to get their head wrapped around.
In this line of code, what we are doing is telling Unity that we want to get the component from the Player script, and the component we wish to grab is the newly made Damage component. Now, when we take damage, we will lose a life. However, with this method of writing the code, there is a greater chance at some error happening. Let’s say the script wasn’t on, what would happen is:
As you can see, we get a NullReference error in our console. This is because there is no player script set on our unit and when the enemy passes through us, it doesn’t recognize the player at all.
If we type it out like so:
This method will prevent any errors from occurring, which will not cause as many issues on the users end of the game. Now, if we get our script back on our player and spawn a couple more enemies, we can see what happens when we get hit 3 times from the enemy:
As we can see, we now have our life system working as intended, and when we take 3 hits from our enemy, we now die in the game.
Now that we have finally finished the enemy part of our game, we can now go through all of the comments that we have no need for them and making sure everything looks clean.
As we can see from above, we have a few things that can be cleaned up in the script. We have some comments that are not necessary, as well we still have the debug.log that we don’t need to have anymore.
Now that we have finished building our enemy script and cleaned it up a bit, we can start working on a spawn system for our enemy so that there is an endless stream of enemies for us to shoot at.