If you’ve been following along, we have a player that can shoot lasers and an enemy that that detects collision. Now, to we are going to add a destroy function to the collisions, add a lives system, and I’m going to teach you how to have your separate scripts communicate to one another.
We have a working collision system already so adding a destroy function will be simple. let’s begin with the laser. We want to write an if statement for if the laser collides with the enemy both the laser and the enemy must be destroyed. We are going to need to destroy the laser first. If we destroy the Enemy the code will stop there once the main object is destroyed.
Remember, when the collision is detected, the Laser is stored in other. When the collision is detected with the laser, the laser will be destroyed, as well as the enemy.
The player will require more of an effort. To begin it would be a good idea to create a lives variable. This way we can control how many hits the player can take before the player is destroyed. To do this we will simply make a private int _Lives = 3 in the player script. Add a Serialize field so we can manipulate the value in the inspector.
Next, we need to create a new method. Public void Destroy(). You may notice that unlike the other methods we have dealt with so far, this one is public. Methods default to private, and we need this method to be public, so we call call upon it with another script.
In this new method we want to write an if statement for what will happen when we take damage. We have already set the number of lives, so we need to be hit three times before we are destroyed. So, when we are hit, we need to lose one life. After three lives destroy the object.
We are almost there now we need to set up communication between the enemy script and the player script. Let’s make our way to the Enemy script to continue. For the Enemy to have access to the player we will need to use the GetComponent command. By default, we always have access to the transform component, and through that we will use Unity’s hierarchy system to gain access to the player script component.
Now let’s break this line down. Other is storying the player. Transform.GetComponent is the formula to get the component you need on the selected Object. <Player>() is the name of the component. and Damage() is the public method we created. () Is calling that method to action. Now the formula in the Damage method will be run when this code is activated.
Now you know how to have one script communicate with another. This is the first major wall that new developers have trouble with, so I would suggest practicing GetComponent a few times. The better understanding you have with this function the better your life will be going forward. In the next tutorial we will begin working on a spawn manager. Remember, don’t be afraid to experiment with your code and I’ll see you in the next tutorial.