- Home /
Get string, but not the same twice in a row
I want the player to enter a "password" when asked to in one of my minigames. This password is selected from a string[] by using the following code:
public string GetRandomPassWord(){
return Passwords[Random.Range(0, Passwords.Length)];
}
This is of course working as intended.
Then, I want to check if the last selected password is the same as the new one, but that isn't working correctly yet. What should I change in the following code to fix it?
correctPassword = GetRandomPassWord();
if (lastPass != "") {
if(lastPass == correctPassword){
correctPassword = GetRandomPassWord();
Debug.Log ("Was last pass!");
} else {
lastPass = correctPassword;
}
} else {
lastPass = correctPassword;
}
Answer by fafase · Nov 04, 2015 at 01:09 PM
Are you reusing the passwords or do they have single use?
If so, use a list and remove the entry once they are used. There are plenty on this on UA about unique random number.
If you plan on reusing them later on and you just don't want two identical ones in a row, I would save the previous, find it from the list and create an array without it:
if(string.IsNullOrEmpty(previous) == true)
{
// no problem you have no previous password
}
else
{
List<string>pass = Passwords.ToList();
pass.Remove(previous);
string password = pass[Random.Range(0, pass.Count)];
previous = password;
// continue with identification using password
}
// here previous can be used outside the statement and contain the current password
Your answer
Follow this Question
Related Questions
Strings with Unity 5.0 1 Answer
Ui text to string ? 1 Answer
How can I get string from console text 2 Answers
overlapshere wont convert its hit colliders name to a string 2 Answers
Random String from list of string without repeated letters 2 Answers