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
MediumEach click drops a crate from a random spot over the floor.
- Inside the click's
if, pickfloat x = Random.Range(-4f, 4f);andfloat zthe same way. - 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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch11Prefabs and Spawning
Prefabs and InstantiateSpawn on a TimerSpawn in a GridLists of ObjectsTake Back the NewestDestroyRandom SpawnsRecap: Fireworks6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground