Break
Lesson 6 of 16 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
Medium- In
GameManager, add anint scoreandpublic void BrickBroken(Brick brick), which adds the brick'spointstoscore. - In
Brick, writepublic void Hit(): it tellsGameManager.Instancethat this brick broke, then destroys the brick. - Add
OnCollisionEntertoBrick: when the object taggedBallhits it, callHit().
Press Play, break a few bricks, 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.
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.