Aug
31
2014

[Beginner] Instantiate objects at random positions

**This is our first guest post, simple beginners tutorial for spawning (instantiating) objects at random positions:

——————————-
——————————-

Hello, my name is Liviu Globa i’m an indie developer, making games for about 4 years in Unity. I would like to show you some tips that will make your game better and more interesting.

Today I’ll speak about how to make your game more unpredictable using Unity class Random.

First let’s find pros in random things in a game :
-Randomization gives to your game infinite playability
-Things don’t look mechanic
-Randomization is also used in AI, maps procedural generation etc.

How to program a random position in 3d space(C#)

In this mini Tutorial you will learn how to use Random class in C#, so let’s start with essentials for example let’s place some cubes in random positions into space.

1.Just Create a new empty project, name it how you want to. File->New Project.
2.Create a cube. GameObject->Create Other->Cube.
-by drag’n’droping the cube into Assets folder we will have a prefab of this cube.After that delete the cube.
So this is our experimental cube:

random_tutorial_ss1(click image for full size)
3.Create C# script and name it Generator.
4.Drag’n’Drop Generator script on the Main Camera object.
5.Now open Generator script and edit it like i did:

– we will need a public variable of type GameObject for the prefab of the cube.
– two variables of type int to define minimal and maximum allowed distances.
– and one variable to define how much cubes we want to place in the space.

Your script should have this:

random_tutorial_ss2(click image for full size)


Vector3 GeneratedPosition()
{
 int x,y,z;
 x = Random.Range(min,max);
 y = Random.Range(min,max);
z = Random.Range(min,max);
 return new Vector3(x,y,z);
}

This is the core of lesson, this function generates every time a new vector.Inside this function we can see that there are 3 variables of type int x,y and z and they are generated by itself individually using next method Random.Range(min,max); where min <= random value > max.
*Note: So if min = 0 and max = 100 random value can be {0,1,2,3,4……..97,98,99}.! Without 100.

 

Next step is to place the cubes, we will use for this a for loop and the function Instantiate for placing game objects into the scene:

void PlaceCubes()
{
  for(int i = 0; i < numberOfCubes; i++)
  {
        Instantiate(cube, GeneratedPosition(), Quaternion.identity);
  }
}

So the function PlaceCubes() will place a number of cubes equal with our variable numberOfCubes.

How we can see in Instantiate function we need to put next parameters:
-the object of type GameObject;
-the position of type Vector3;
-the rotation of type Quaternion;
General form : Instantiate(GameObject gameObject,Vector3 position, Quaternion rotation);
6.Now save script by pressing Ctrl + S and got o the Unity Editor.
7.Click on the Main Camera object in the Hierarchy (if you forgot to assign the script to the camera do it!)
8. Put any values in the Inspector, something like this:
random_tutorial_ss4(click image for full size)
9.Click Play and you will see this (depends on your values)
random_tutorial_ss3(click image for full size)
Every time you will see something different.This is the fun of randomization that Unity and scripting can ofer to your game.
Random Class can offer you more possibilities then just randomizating an integer,for example you there are functions that will help you to get a random point inside a circle, inside a sphere etc. if you need to visit great unity documentation:
http://docs.unity3d.com/ScriptReference/Random.html

Full source code download:
https://dl.dropboxusercontent.com/u/94477658/Tutorial_1_Random_by_Liviu%20Globa/Generator.cs

You can contact me on mail : globaliviu(at)mail.ru

Also you can follow some of my projects on facebook: https://www.facebook.com/creatix.entertainment.official

I would like to help you out.
Thank you for reading,
Globa Liviu

—————————————–


1 Comment + Add Comment

  • Hello,
    Great article, I really appreciate the simple approach you chose in order to achieve this 🙂
    With that in mind, I would like to ask you for an advice:
    How would you ensure that objects do not overlap or even touch with each other?

    Thank you and keep up the great work!

Leave a comment

Connect

Twitter View LinkedIn profile Youtube Youtube Join Discord Twitch

UnityLauncherPro

Get UnityLauncherPRO and work faster with Unity Projects!
*free unity hub alternative

@unitycoder_com

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.