Script Communication in Unity using GetComponent<T>

Anurag Chawla
2 min readApr 7, 2021

--

As we getting deeper and deeper in our use case of Player, Lasers and Enemies - for Our GalaxyShooter -2D.Unity API Scripting methods — GetComponent<T> plays a vital role here to communicate between these GameObjects.

Take an example, how one can destroyed the Player when Enemy collide with it — both of these Game Objects having scripts.

Note : Consider here Player Script as below having Damage Method.This method reduces the Player _lives by one which is initially set to 3 and when _lives<1 then Player get destroyed

Player Script- Damage Method , that destroy the Game Object when _lives < 1

When Enemy collide with Player/Laser , as per below script -Its having onTriggerEnter event called containing other of type Collider as parameter— where other can use to find who collided with Enemy.

In our case say Enemy collided with Player. Other.tag ==”Player ” condition sets true . Then Player reference (communication of Player from enemy) can be found from GetComponent<T> where T:Player. If Player ref is found and if it’s not null- call the Damage method of the Player.

Script Communication between Player and Enemy using GetComponent<T>

Player can be destroyed further as each time collided with the enemy reduces the live of Player by one and finally reduces to 0 as shown below..

Player Destroyed as _Lives reduces to 0

This concludes Script Communication using GetComponent<T>where T:GameObject

@GameDevHQ-Day 10…

--

--

Anurag Chawla
Anurag Chawla

Written by Anurag Chawla

Emerging Technologies - Power Virtual Agents | AI Chatbots | Multi-Cloud & DevOps | UI Technologies - React , Angular | Gaming Technolgies - Unity, XR- AR/VR

No responses yet