What Did I Hit?
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 9 of 63.
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
EasyDrive the snowplow with the arrows (already written) and give it a job. The two white blocks are tagged Snow.
- When the plow runs into an object tagged
Snow, destroy that block, add 1 to a count and log it:Cleared 1,Cleared 2. - Everything else the plow touches, the ground and the wall included, stays where it is.
Press Play and clear the road, 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
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall