n900orbit
n900orbit

Reputation: 3

Unity3d: Random.Range() Not working the way I intended

I'm spawning objects from a list and so-far i got them to find a parent object that's already live in the scene.The problem is Random.Range() isn't working like I want. I want the listed Objects to spawn to a random parent, instead, they're spawning to the they're parent relative to the order of the list.

Ex. 0,1,2,3,4,5,6,7,8,9 = Bad Ex. 8,3,1,4,6,3,7,9,5,2 = Good lol

var theRange = Random.Range(obj1.Length,obj1.Length);
    for(var i: int = 0; i < theRange; i++){
        var obj2 : GameObject = obj1[i];
        if(obj2.transform.childCount == 0){
        objfromList.transform.parent = obj2.transform;
        objfromList.transform.localPosition = Vector3(0,-2,0);
    }
    }

Deeply thankful

Upvotes: 0

Views: 850

Answers (1)

Jerdak
Jerdak

Reputation: 4056

Following up on my comment, it sounds like you just want a shuffle function. Here is a simple Fisher-Yates shuffle:

void shuffle(int[] a){
    for(int i = a.Length-1; i>=0; i--){
        int j = Random.Range(0,i);
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }
}

void usage(){
    int[] a = {0,1,2,3,4,5}; // assumes obj1.Length = 6
    shuffle(a);
    for(int i = 0; i < a.Length; i++){
        GameObject obj2 = obj1[a[i]];
        GameObject objFromList = GetNextObject(); // dummy method grabbing next list object

        objFromList.transform.parent = obj2.transform;
        objFromList.transform.localPosition = Vector3(0,-2,0);
    }
}

This should get you part way to what you need. If the order of obj1 isn't important you can shuffle it directly instead of using a secondary array like a in my example.

Upvotes: 1

Related Questions