Menu
CoddyTech

What Did I Hit?

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 9 of 71.

The Collision that Unity passes to OnCollisionEnter describes the other side of the contact. collision.gameObject is the object you ran into, so collision.gameObject.name is its name, and collision.gameObject.CompareTag("Hazard") asks for its tag. (collision.collider is the exact collider you touched, when an object has several.)

This bumper car logs everything it bumps into and complains about hazards:

void OnCollisionEnter(Collision collision)
{
    Debug.Log("Bumped into " + collision.gameObject.name);
    if (collision.gameObject.CompareTag("Hazard"))
    {
        Debug.Log("Ouch!");
    }
}

The first line it logs is Bumped into Floor, the moment the game starts: the floor it stands on is a collision too. So a script that reacts to hits always asks what it hit first. Watch which object you name: CompareTag("Hazard") on its own asks about your own object, and Destroy(gameObject) destroys your own object, while Destroy(collision.gameObject) removes the one you hit.

challenge icon

Challenge

Easy

Give the snowplow a job: clear the blocks tagged Snow.

  1. Add void OnCollisionEnter(Collision collision) to Plow, acting only when collision.gameObject.CompareTag("Snow").
  2. Inside, Destroy(collision.gameObject);, add 1 to a cleared field and log "Cleared " + cleared.

Press Play and drive into the snow: each block vanishes and the Console counts it. Then Check.

Try it yourself

using UnityEngine;

public class Plow : MonoBehaviour
{
    public float speed = 3f;
    private Rigidbody rb;
    private int cleared;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        float h = Input.GetAxisRaw("Horizontal");
        rb.linearVelocity = new Vector3(h * speed, rb.linearVelocity.y, 0);
    }

    // Snow the plow runs into: destroy it, count it and log the count
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground