Menu
CoddyTech

Drops

Lesson 13 of 16 in Coddy's Unity Game: Brick Breaker course.

A broken brick sometimes drops a power-up that falls toward the paddle. Whether it drops is a roll: Random.value is a random float from 0 to 1, so Random.value < 0.15f is true about 15 times in 100. Keeping the chance in a field lets you tune it, and lets a test set it to 1 for a drop every time or to 0 for none.

Which power-up drops is a second roll: a random index into an array of prefabs. Random.Range with ints leaves out its maximum, so Random.Range(0, array.Length) can pick every element. An enemy's loot:

public GameObject[] loot;
public float lootChance = 0.25f;

void DropLoot()
{
    if (Random.value >= lootChance) return;
    int pick = Random.Range(0, loot.Length);
    Instantiate(loot[pick], transform.position, Quaternion.identity);
}

A power-up falls at a steady speed by moving itself every frame, and destroys itself once it is below the play area, so missed ones do not pile up. Its prefab has a kinematic Rigidbody and a trigger collider, so the physics knows it moves and it will be able to tell when it reaches the paddle.

challenge icon

Challenge

Hard
  1. In PowerUp, add public float fallSpeed = 3f and public float bottomY = -9f. In Update(), move down at fallSpeed units a second, and destroy the power-up once its y is below bottomY.
  2. In GameManager, add public GameObject[] powerUps (the scene links the WidePowerUp and MultiPowerUp prefabs) and public float dropChance = 0.15f.
  3. In BrickBroken, with a chance of dropChance, make a random one of powerUps where the brick was.

The power-ups fall through the paddle for now: catching them comes next.

Press Play, break bricks until one drops, then Check.

Try it yourself

using UnityEngine;

public class PowerUp : MonoBehaviour
{
    // The last chapter: power-ups that fall from broken bricks.
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Game: Brick Breaker