Utilising Random.Range in Unity to Give Our Enemies A Random Respawn Location

Objective: To show you a way how to use the Random.Range method by giving our enemies a random respawn location in Unity.

Right now the enemies in my game spawn at the top of the screen and simply move down towards the player. I have a couple options here as to whether I simply let the enemy Destroy itself off the screen and Instantiate a new one, or an alternative that could spice the game up a little bit, is to have the enemy respawn at a random location back at the top of the screen and if the player wasn’t able to destroy the enemy the first time. Later on I will add more spawning enemies, so this enemy build up could get quite intense if the player isn’t able to Destroy them!

Within our enemy script let’s add the following code and break it down:

transform.Translate(Vector3.down * enemySpeed * Time.deltaTime);
// Previously explained, but a simple movement script to move the enemy down

if(transform.position.y < -5)
{

// If the enemies transform position is below -5, then we want to run the following code:

float randomX = Random.Range(-8f, 8f);
// Create a new float variable called RandomX, and get it to generate a number between it’s minimum (-8f) and it’s maximum (8f).

Note: Be careful here if you are using an int data type for Random.Range as the minimum number is inclusive but the maximum number is exclusive. Meaning that if we used 8 for a maximum number, it would only generate a number up to 7. Using the float data type doesn’t have the same issue, both the minimum and maximum are inclusive.

transform.position = new Vector3(randomX, 6, 0);
}

// Take the enemies current transform position and assign it a new Vector3 with coordinates of (randomX, 6, 0) along the X, Y, Z axis respectively.

Watch the magic happen:

Useful Links
https://docs.unity3d.com/ScriptReference/Random.Range.html

--

--

Passionate Unity Game Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store