Give me that script! GetComponent and Script Communication.

There comes a time where you have to have one script, tell another script to do something. You may not technically have to and could do it another way, but it would be most ideal and more simple to do it that way.

Creating a lives system for my game is one of them.

My player needs lives as being immortal would be a little boring but how do I lose them? I get hit, simple. So first, where would we keep track of the lives? That would be within the player script as a Lives int Variable.

Now, I don’t want this lives variable to be touched by anything other than the player script so we will keep it private. In reality there is no need to in this game. I want the player script to be the one to control it. However, I need to make some kind of process in which when a enemy hits me, I lose a life, and if I hit 0 lives, I die.

We can make the act of the player taking the damage inside of the Player script itself like this with its own method that is PUBLIC called Damage(). With this, although I have made the variable private, this method is public and could be used by other scripts, but then I had to figure out how to actually get that to work.

Now in the enemy script, if we go back to our code from the OnTriggerEnter article, one thing to understand is that with the collision, you retain the data of what you collided with. With that we can pull the script from it by using GetComponent<TheScriptName>() and creating a variable that will hold that script as a type Player variable called player. This confused me at first but the Component I am getting is called Player, so its just a Variable that holds, the Player Component!

Afterwards it is just as simple as doing player.Damage() or whatever method you wanted to use within that script as the enemy now has a hold and access to the Player Component as it is stored in the variable now.

With this, every time the enemy collides with the player, it will run the Damage() method on the player script which will reduce the lives variable on the player by 1. If I get to 0, my player dies.

Script communication can be hard, and there are other ways to do it such as finding the GameObject, whether it be by tag, or just searching the name. It is essential also to minimize the overuse of GetComponent as it is a fairly intensive action. Get it once at a certain part of the code so you would only need to get it once.

The prototype is almost done and soon I will have a game that actually looks like ships shooting at each other.

Lets keep going to the finished prototype! See you again next article.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store