Random Spawns
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 53 of 67.
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
MediumEach click should drop a crate from a random spot over the floor:
- x and z: each any value from -4 to 4, not only whole numbers;
- y: 5, so the crate falls onto the floor;
- no rotation.
Press Play and click a few times, 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
}
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon6GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch9Prefabs and Spawning
Prefabs and InstantiateSpawn on a TimerSpawn in a GridLists of ObjectsDestroyRandom SpawnsRecap: Fireworks