Damaging the Player with GetComponent

David Little
3 min readJun 15, 2021

Now that the Enemy gameObjects can be destroyed with collisions and fire from the Laser, we’re now going to add lives and damage for the Player.

The process for this is a simple one. Basically we want to give the player some lives that can then be taken away as a result of damage from the enemy gameObjects. First the lives.

We open up the Player script and a new variable. It will be called, you guessed it lives, and we will start with three of them. But, we’ll make it a private one so that it cannot me messed with by other parts of the game. That looks like this…

Then we scroll down and add a new method to the script called Damage. That part looks like this…

This Damage method, whenever it is used, looks at the number of lives that the player currently has and subtracts one from that amount. This method also provides the function of ‘death’ for the player when the current number of lives minus the damage is less than one, at which time the script will destroy the player gameObject.

To apply damage to the player we now turn our attention to the Enemy gameObject. Last time we added code that would destroy the Enemy if hit by a laser. Inside that same method we will put a section that checks first to see if the Enemy has collided with the Player. To do this we need to get information from the Player script over to the Enemy script and we do this using GetComponent. Using GetComponent in the Enemy script tells it to take a look at the Player script’s output. Specifically, we’ll be getting the Enemy to check if it did damage to the Player with what’s called GetComponent.

This allows the Enemy gameObject to get the component called Player and cause damage to it. And, we want to check to be sure we’re calling something that exists to avoid errors. We add a null check to do this, before damage is done. That looks like this…

…which is saying that if the player is not equal to zero, do damage to the player. And, if you’re wondering, != means not equal. So if the player is not there, does equal zero, then it will just skip on to the next operation.

Now, every time our Player object collides with an Enemy object it will inflict damage by taking away a life and destroying the Player object if its number of lives drops below 1.

--

--