Menu
CoddyTech

Drops

Lesson 14 of 19 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

Broken bricks sometimes drop a power-up.

  1. In PowerUp, add fallSpeed = 3f and bottomY = -9f; in Update(), fall at fallSpeed a second and destroy it below bottomY.
  2. In GameManager, add public GameObject[] powerUps; and public float dropChance = 0.15f;
  3. In BrickBroken, if Random.value < dropChance, instantiate powerUps[Random.Range(0, powerUps.Length)] at the brick's position.

Press Play and break bricks: now and then one drops a power-up (catching comes next). Then Check.

Try it yourself

using UnityEngine;

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

All lessons in Unity Game: Brick Breaker

Practice on your own: Unity playground