Question by
andrianohnoo · Feb 07, 2016 at 05:30 PM ·
unity 5javascriptarrayrandomarrays
how to not repeat random array
hey, im new at unity. I got a little problem, im using array to random gameobject, but i want no repeating twice on that gameobject, here my script
var q1 : GameObject;
var q2 : GameObject;
var q3 : GameObject;
var q4 : GameObject;
var q5 : GameObject;
var q6 : GameObject;
var q7 : GameObject;
var q8 : GameObject;
var q9 : GameObject;
var q10 : GameObject;
var randomQuestion : Array;
function Awake (){
randomQuestion = new Array(q1,q2,q3,q4,q5,q6,q7,q8,q9,q10);
}
function Start(){
var chooserandom = Random.Range(0,(randomQuestion.length));
var position = transform.TransformPoint(Random.Range(-3,-3),1,Random.Range(5,5));
Instantiate(randomQuestion[chooserandom],position,Quaternion.identity);
}
Comment
Answer by LLIV · Feb 07, 2016 at 08:50 PM
var randomTracker = new Array (false,false,false,false...); //Define this outside the loop
var UnusedRandom = new Array();
for (var i =0;i<randomQuestion.length; i++){
if (!randomTracker[i]){
UnusedRandom.push(randomQuestion[i]);
}
}
var chooserandom = Random.Range(0,(UnusedRandom.length));
Instantiate(randomQuestion[chooserandom],position,Quaternion.identity);
randomTracker[chooserandom] = true;
This should work for what you're trying to do. Keep in mind the randomTracker has to be the same length as the randomQuestion array for this to work. The benefit of this is you can set which questions you want to use fairly easily.