moving random objects to random positions


I’m attempting to make a small demo game for learning experience.
I have 10 different objects which I’m trying to move to a random location depending on the level.

at level one, a total of 6 objects should be moved.
4 of them should be chosen at random and 2 of them should be of the same kind.

at level 2, 8 objects should be moved. 4 random objects and 2 of the same kind.

The function would look like 4+(2*level)

I have a list of all the objects
public Transform _object;

Does anyone know how to do this with code? I’m guessing I need to call a custom function with the level and then choose an object and make 2 of them at a random position and choose
(number - 2) random objects and spawn each of them at a random position.

Hopefully that made sense. Thanks :slight_smile:

Something like this is what you are looking for, or should get you started, I think:

    // Loop for each object, minus 1 because the last one we will duplicate so we have 2 of the same.
    int count = 3 + (2 * LevelNumber);
    for (int i = 0; i < count; i++)
        // Pick our random object type
        int r = Random.Range(0, _object.Length - 1);

        // Ugly code loop to handle the duplicate (change this to better syntax/layout)
        while (true)
            // Create a copy of this object type (I'll leave it to you to figure out how to destroy at end of level, if needed)
            GameObject obj = (GameObject)GameObject.Instantiate(_object[r]);

            // Calculate random values for X,Y,Z and set location of new object
            float x = Random.Range(MinX, MaxX);
            float y = Random.Range(MinY, MaxY);
            float z = Random.Range(MinZ, MaxZ);
            obj.transform.position = new Vector3(x, y, z);

            // If this is our last object, do one more of these inside loops to create 1 more of same time.
            if (i + 1 == count)


_object = an array containing your different types of object, just 1 of each object type.

LevelNumber = you’ll have to figure this one out, I keep a global variable in my games and update it anytime I change levels, you can do the same if you want

MinX, MaxX, MinY, MaxY, MinZ, MaxZ = you’ll want to define these variables or just replace them with whatever min/max values you want for the spawn locations (i.e.-depends on the max size of your “world”). If you don’t want one axis to be random, just make it a fixed value.

Please don’t use this code as-is, change it to a better syntax, I just like code I can copy/paste as a single part and not multiple functions for a simple example – plus, I don’t like spending too much time writing perfect code for others to copy/paste vs learn :slight_smile: