Unity – Detect gameObject’s tag via OnCollisionEnter()

I’ve struggled for a long time with Collisions in Unity, and for some reason avoided using the OnCollisionEnter() function, and favouring OnTriggerEnter() instead.

This was because OnTriggerEnter() allows access to the collider directly, allowing me to write this (from BotSumo):

function OnTriggerEnter(other: Collider) {
   //--when player touches pickup
   if (other.tag == "Player" && isCollectable) {

But this requires one of the objects colliding to be a trigger. For a pickup, this is ok, but for my new game, the two objects are speceships colliding in space, which I want to bounce apart, then explode after a few seconds.

For an OnCollisionEnter function, you have to inspect the “Collision” object, which for a while put me off, because I didn’t quite understand it. Turns out though it;’s quite easy. You can get the other object simply by collision.collider.

And in the function I’m currently writing, I need the object’s tag (to see if it’s an enemy), which I can get too. Here’s my function:

function OnCollisionEnter(collision: Collision) {
   Debug.Log("collision "+ collision);

    if(collision.collider.tag == "Enemy"){
      Debug.Log("hit enemy");
      isAlive = false;

I’m leaving this here because I know I’ll need it later, and sometimes searching for snippets of code like this isn’t easy in Unity’s documentation.