reate a simple 3D scene in Unity where the player controls a sphere (Player), collects coins (Coins), and avoids or takes damage from enemies (Enemies). The task reinforces the use of OnCollisionEnter and OnTriggerEnter, their differences, and limitations.
- Create a
Plane— the ground. - Add a
Sphere— the player. Assign to it:Rigidbody(non-kinematic,isKinematic = false)Collider(leaveIsTrigger = false)- A script
PlayerControllerfor movement with arrow keys/WASD (or use standardMoveTowards).
- Add 5–10 cubes with the tag
"Coin", colored green. They should have:Colliderwith IsTrigger = true- An empty script (or just the tag).
- Add 3 red cubes with the tag
"Enemy". They should have:Collider(IsTrigger = false)Rigidbody(kinematic or not — your choice, but at least one Rigidbody must exist in the scene for collisions).
Write a script PlayerCollisionHandler that contains:
- Stores the values of
scoreandhealth OnTriggerEnter(Collider other)- Collision with a coin- Verification via
CompareTag("Coin") - Increases the value of the
score - Destroys the coin (
Destroy) - Displays the message
"Coin collected! Score: " + score
- Verification via
OnCollisionEnter(Collision collision)- Clash with the enemy- Verification via
GameObject.CompareTag("Enemy") - Reduces the value of
health - Displays the message
"Damage! Health: " + health - When
health <= 0displays the message"Game over!"
- Verification via
- Upon colliding with an enemy, the player should bounce back (use
Rigidbody.AddForce). - Play a simple sound when collecting a coin (optional).
- Add a wall with a trigger zone that teleports the player to another point on
OnTriggerEnter(useTransform.position).
- Why is
OnTriggerEnterused for collecting coins instead ofOnCollisionEnter? - What would happen if you removed the
Rigidbodyfrom a coin? What if you made its collider non-trigger? - Why is
OnCollisionEnterused for collision with an enemy?
Write working code, set up the scene, and ensure that:
- Coins disappear on touch and increase the score.
- Enemies reduce health and push the player away.
- The trigger zone teleports the player.