Randomization of Objects

I want to randomize where my objects spawn in my scene. but have no idea how to go about it.

2 Answers

2

You'd want to make a variable containing a Vector3 type of data. This is how I would do it:

    var object : Transform;
    // The gameobject you want to instantiate

        function Start() {

        var position = Vector3(Random.Range(10, -10), Random.Range(10, -10), Random.Range(10, -10));
// This creates a position in space between these values (x, y and z)        

        Instantiate(object, position, Quaternion.identity);
// This instantiates the object in the position

        }

They could also use Random.insideUnitSphere or Random.onUnitSphere.

Yeah... That's right, but I wanted to be a bit more clear.

Bumbaz's answer describes how to randomize a Vector3 (position).

Some games instead have a list of multiple spawning points, and randomly pick which one to spawn the next enemy/powerup/etc at. One way to do this would be to have an array of Vectors, set in the inspector. Then you'd pick an array index at random, and use the Vector3 that was stored at that index.

Here's a graphical way to do the same thing. Create a SpawnPoint script and assign it to a bunch of GameObjects around the scene. These mark the places where spawning happens.

Then when the scene first loads, call FindObjectsOfType to get an array of all SpawnPoint objects in the scene. Now you just generate a random index from 0 to (count-1) whenever you want to pick the next spawning point.

Once you have a position, you would Instantiate the enemy at that position, as Bumbaz's answer already demonstrates.