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
EasyGive the snowplow a job: clear the blocks tagged Snow.
- Add
void OnCollisionEnter(Collision collision)toPlow, acting only whencollision.gameObject.CompareTag("Snow"). - Inside,
Destroy(collision.gameObject);, add 1 to aclearedfield 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
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable WallPractice on your own: Unity playground