Unity Random generation

Random generation for mobile games in Unity

Random generation in Unity gets harder the more advanced generation you want. This tutorial will show how to generate an array of random object with boundaries of the user’s screen size. This code will be for a 2D game but can be used in 3D games just by changing some components.

Random Generation

Start by creating an empty object in your hierarchy, I will name mine ObjectSpawner. You will attach a C# script on the ObjectSpawner called DeployObjects.

Step 1

Now its time to code, so what do we need for the random generation to work? For instance, you want a list of game objects, which is gonna hold all the prefabs you want to randomly generate onto the scene. The project is gonna make random generation start from the highest point in the Y-axis and rain down to the lowest point in Y. In other words, we have to use Vector2 for screen bounds.

After you have made your variables its time to initialize the variables in the unity start function. We have to initialize screen bounds. Therefore, we set ScreenBounds equal to our main camera’s set values. This defines the boundaries of our screen to an X and Y-axis.

We need a function that will spawn objects, and a timer so we can do it as frequently we would like. For the spawning, we will instantiate an object from our prefab list and randomly select an object by using a random integer for the index. After that, the position of the object will be set randomly based on the screen bounds. How often we use this function is up to the developer. Similarly, respawn time can be set to 1 or spawn in even faster intervals.

You finished the code! After that, drag the prefabs you want to spawn into the script. Remember that the objects need to have a rigid body for this to work. Good luck forward on your game!

Random Generation Step 2

Try our new mobile game, Ocean Roads for free on google play store!