- Home /
How to create a random array avoiding repeat same value
Hi guys,
I have created an array which displays random instructions but I don't want that the instructions will repeat once have been displayed. Using the code below the instructions are not displayed. Any ideas why?
Thanks in advance for your help.
static var randomInstruction:int;
static var randomVariable:String;
private var showingObject : boolean = true;
static var objectToBeFound:int;
static var GeneratedNumbers :int[];
static var objectsInstructions = new String [3];
objectsInstructions [0] = "keys";
objectsInstructions [1] = "sun";
objectsInstructions [2] = "star";
objectsInstructions [3] = "pencil";
static function GenerateNumbers ():int
{
randomInstruction = Random.Range (0,objectsInstructions.Length);
while (GeneratedNumbers[randomInstruction] == randomInstruction)
{
randomInstruction = Random.Range (0,objectsInstructions.Length);
}
GeneratedNumbers[randomInstruction] = randomInstruction;
return randomInstruction;
}
function Start ()
{
randomInstruction = GenerateNumbers();
randomVariable = objectsInstructions[randomInstruction];
nrOfObjects = nrOfObjects++;
objectToBeFound = randomInstruction;
yield new WaitForSeconds (5);
yield WaitForSeconds(9);
showingObject = false;
GeneratedNumbers= new int[3];
for (var i = 0; i < GeneratedNumbers.Length; i++)
{
GeneratedNumbers[i]=-1;
}
}
function OnGUI ()
{
GUI.skin=customSkin;
if(showingObject)
{
GUI.Box(Rect(75, 650, 900, 80), randomVariable);
}
}
Answer by robertbu · Feb 27, 2013 at 04:51 PM
A typical way to solve this problems is to shuffle them. You can either shuffle the string directly, or you can shuffle a parallel list of integers and use them as indexes into the list.
As easy shuffle algorithm is to generate two random indices and then swap the values at those indices. Repeat some number of times.
Then when you go to use them, you maintain an index and use the entries in order.
Your answer
![](https://koobas.hobune.stream/wayback/20220613093516im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
how to randomly pick a string from an array 3 Answers
Filling GUI.BeginScrollView with images 1 Answer
Custom Inspector GUI, Instantiating some classes 2 Answers
GUI is not staying where it should 1 Answer
Mysterious crash involving an array 2 Answers