Script Communication in Unity using GetComponent

Lance Gold
3 min readMar 31, 2024

--

In the example, there are three C# scripts coding three classes named Laser.cs, Enemy.cs, and Player.cs

We have a private variable in Player to value the number of remaining lives available to lose.

public class Player : MonoBehaviour
{
[SerializeField]
private int _lives = 4;
...

And the setter function accessible from outside the class (outside the .cs file)

public class Player : MonoBehaviour
{
[SerializeField]
private int _lives = 4;

public void Damage()
{
_lives--;

if (_lives < 1 ) // !_lives only works if _lives is type boolean
{
Destroy(this.gameObject);
}
}
...

From the Enemy.cs file we can access the public method in the Player class

Open the Enemy.cs file tab

When the Enemy gameObject collides with a Player gameObject, first damage the Player, then Destroy() the Enemy.

    private void OnTriggerEnter(Collider other)
{
// if other.name is Player
// damage player
// destroy this Enemy

if (other.tag == "Player")
{
other.transform.GetComponent<Player>().Damage();
Destroy(this.gameObject);
}
...

For a moment, take a look at the <Player> csharp syntax. Consider the < > syntax outside of Unity.

Generic Methods — C# Programming Guide — C# | Microsoft Learn

The class contained in the < >’s would be a type in other programs. Here is the Microsoft Learn example:

public static void TestSwap()
{
int a = 1;
int b = 2;

Swap<int>(ref a, ref b);
System.Console.WriteLine(a + " " + b);
}

Instead of writing a different Swap function for int, float, and decimal types, simply specify which type (int, float, decimal) is desired and include inside the < >’s.

Here is the Swap declaration:

static void Swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}

in the Swap function, there is no mention of int, float, or decimal.

so to use Swap with two int’s:

Swap<int>( a,b );

to Swap with two float’s: Swap<float>( f, g );

Swap<float>( f,g );

Return to Unity coding…

to call the Damage() method inside the Player class, use type Player:

The Player component in the Inspector view
            other.transform.GetComponent<Player>().Damage();

to return the “color” value inside the MeshRenderer class of Player, use type “MeshRenderer”:

Components of gameObject Player in Inpector view
other.transform.GetComponent<MeshRenderer>().Material.color;

Next is the best programming practice to check if the type (the class) exists.

    private void OnTriggerEnter(Collider other)
{
// if other.name is Player
// damage player
// destroy this Enemy

if (other.tag == "Player")
{
Player player = other.transform.GetComponent<Player>();

if( player != null )
{
player.Damage();
}
Destroy(this.gameObject);
}
...

--

--

No responses yet