Script communication in unity using GetComponent:

Sudarshan Thube
2 min readJan 13, 2022

In last article we see about colliders and unity physics and how to use it. In this article we are going to see how to use OnCollisionEnter and OnTriggerEnter in our game.

Now, we need to write code in laser script or enemy script to detect collision. Remember that, to make it work we need to write collision any one of them, if we write code for both object then it may give some error or cause bug in game.

If condition to check the collided object is laser and player.

In above code we are checking the tag of triggered object, if Player collide with enemy ship then player will take damage and if it is Laser then player’s score increase and enemy ship get destroyed.

Here, To get access component from player, laser or any collided object we can use GetComponent<>(). Like in above code, if objects tag is Player then we will access Player script from that object.

By using same code we can access any component present on object collide with enemy ship.

Now, lets check collider setting on enemy, laser and player so that above code will work. Edit collider size if it not matching with object.

Tool to edit collider.

Then check Is Trigger in enemy ship, so that we can use OnTriggerEnter and because of its 2d collider we have to use OnTriggerEnter2D.

Now, lets check out if our code is working or not.

Great, Enemy ship get destroyed when it collide with laser as well as player.

In next article we will see get some graphics for our game and then use it.

--

--