- Home /
How can stop the repeat random number (Random.Range)
How can stop the repeat random number. i am going to paste my code.please have a look.
#pragma strict
var NameArray : String[] = ["apple","kite","knife","man","rat","name"];
var chosenName : String;
function ChooseName()
{
chosenName = NameArray[Random.Range(0, NameArray.length)];
//var chosenName = NameArray[Mathf.floor(Random.Range() * NameArray.length)];
Debug.Log("chosenName " + chosenName);
}
function OnGUI()
{
if (GUI.Button(Rect(10, 10, 100, 35), "random")) {ChooseName() ;}
GUI.Box (Rect(120, 10, 100, 35), "" + chosenName);
}
function Start(){
InvokeRepeating ("ChooseName", 0, 10);
//ChooseName();
}
What does it mean "repeat"? You have several object to name? Or is it always the same name every time you start a game?
Answer by agies1 · Jan 11, 2014 at 04:03 PM
If I understand correctly you are looking to get a non-repeating random name. We can try something where we remove the selected name from the array each call. If we run out of names we reset the collection from the original template.
var NameArrayTemplate : String[] = ["apple","kite","knife","man","rat","name"];
// Using Unity JS Lists
var NameArray : List.<String> = new List.<String>(NameArrayTemplate);
function chooseAName() : String{
var index = Random.Range(0, NameArray.Count);
chosenName = NameArray[index];
NameArray.RemoveAt(index);
if (NameArray.Count == 0)
NameArray.AddRange(NameArrayTemplate);
return chosenName;
}
Because I switched to a List, the property should be Count and not length, sorry.
Answer by robertbu · Jan 11, 2014 at 03:27 PM
The typical solution is to first shuffle the array (randomly swap elements for some number of iterations) in Start(). Then you select them in order until the list is empty. Alternately you can put your strings in a generic list and remove the string from the list as it is selected.
See the generic list section here:
http://wiki.unity3d.com/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use?
Your answer
![](https://koobas.hobune.stream/wayback/20220613130108im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Make tranform follow raycast 1 Answer
Pressing Two Buttons At The Same Time it not working 0 Answers
Problems making character hang on walls 0 Answers
function OnCollosionEnter problems 1 Answer