Can you hear me Now? — Script Communication in Unity

Games Woods
3 min readMay 6, 2021
Photo by Pavan Trikutam on Unsplash

The concept of communication between your script components in Unity (and in software engineering in general) is hugely important. Our trusty 2D space shooter will help me illustrate the why and the how of it all.

Objective: Access a Component from one script Enemy.cs → OnTriggerEnter to another Player.cs → Damage();

Implementation:

The first step is to introduce the concept of lives in our game. We’ll start our player off with 3 lives.

In the Player.cs script we create a Serialized Field/private int called _lives and give it a value of 3.

Next we need to create a method that will subtract 1 from the player’s _lives variable. Now in order to have access to this method we need to make it public. By default the only elements that we have access to from script to script are its transforms. The method I created is called Damage(). All it does when called is to remove 1 live from the _lives variable. It also checked to see if the _lives are less than 1 → Destroy the player Object.

Now to the heart of the matter! How do we call the public Damage() method we just created. We jump back to the enemy script since that is where we have our OnTriggerEnter method checking to see if we have collided with the player or if we(the Enemy) has been hit by a laser.

Let’s breakdown how we accessed the Damage() method in the Player script from Enemy script.

In our OnTriggerEnter(Collider other) The other is a variable that stores the name of objects that we collide with. In the next statement we telling the script that if the object that we collided with has a tag of “Player”. We then access the public elements of the player script that we need. In our case the Damage() method.

Check for Null — You’ll notice that after we’ve called the player script we add another if statement qualifies to see that we do have a Player object or as its written we check to make sure that it is not null. A common error in programming is the dreaded Null exception error which has cause more crashes than most would like to admit. IF we run our game and focus on the Player script inspector we can see our lives reducing every-time we are hit!

All this via Script communication!

Life Countdown

--

--