Menu
CoddyTech

Random Spawns

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 68 of 85.

Random.Range(min, max) picks a random number, and what it can return depends on the type of the numbers you give it. With floats, any value from min to max can come out, both ends included. With ints, max itself is left out. A dice roll therefore asks for 1 to 7:

int roll = Random.Range(1, 7);   // 1, 2, 3, 4, 5 or 6
Debug.Log("You rolled " + roll);

The int version leaves out max so that Random.Range(0, names.Length) is always a valid array index. It also means Random.Range(-5, 5) gives only the whole numbers from -5 to 4, even when you store the result in a float. Write Random.Range(-5f, 5f) for any value in between.

For spots and directions in 3D, Unity has two ready-made random vectors. Random.insideUnitSphere is a random point inside a ball of radius 1 around (0, 0, 0). Random.onUnitSphere is a random point on that ball's surface, which makes it a random direction of length 1. transform.position + Random.insideUnitSphere * 2f is a spot up to 2 units away in any direction, up and down included.

challenge icon

Challenge

Medium

Each click drops a crate from a random spot over the floor.

  1. Inside the click's if, pick float x = Random.Range(-4f, 4f); and float z the same way.
  2. Call Instantiate(cratePrefab, new Vector3(x, 5, z), Quaternion.identity);.

Press Play and click a few times: crates fall in new places. Then Check.

Try it yourself

using UnityEngine;

public class CrateDropper : MonoBehaviour
{
    public GameObject cratePrefab;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            // Drop a crate from a random spot: x and z from -4 to 4, y = 5
        }
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground