Break
Lesson 6 of 19 in Coddy's Unity Game: Brick Breaker course.
The bricks have no Rigidbody, but the ball has one, and Unity sends OnCollisionEnter to both objects in a collision. So a brick can notice the hit itself. In the brick's script, gameObject is the brick and collision.gameObject is the thing that hit it.
The score belongs to the GameManager, and bricks are copies of a prefab. A prefab is an asset outside the scene, so its fields cannot point at the scene's GameManager in the Inspector. The GameManager sets the static GameManager.Instance to itself in Awake(), so any script can reach it, prefab copies too.
A vase that shatters when the player runs into it:
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Player")) Shatter();
}
public void Shatter()
{
Destroy(gameObject);
}Destroy(gameObject) removes the vase. Destroy(collision.gameObject) would remove the player, and Destroy(this) removes only the script, leaving the vase standing. Keeping the break in its own public method means other code, a bomb or a power-up, can break the vase too.
Challenge
MediumThe ball breaks bricks and scores their points.
- In
GameManager, addint score;andpublic void BrickBroken(Brick brick), which addsbrick.pointsto score. - In
Brick, writepublic void Hit():GameManager.Instance.BrickBroken(this);, thenDestroy(gameObject); - In Brick's
OnCollisionEnter, callHit()when the object is taggedBall.
Press Play and launch: each brick the ball hits vanishes. Then Check.
Try it yourself
using UnityEngine;
public class Brick : MonoBehaviour
{
public int points = 10;
// Next: the ball breaks a brick and scores its points.
}
All lessons in Unity Game: Brick Breaker
Practice on your own: Unity playground