- Home /
Checking that this String is in this Array
Hi, i want to make something like cheat console using text field and array of cheats strings. And when i type for example player.kill in text field unity will search if this string is in Cheats
Strings Array and make an Label "Succeed" when it is and "Failed" when it's not.
Thanks in advance and sorry for my English.
Answer by Eric5h5 · Feb 09, 2013 at 08:38 PM
You don't need to loop through arrays or anything, just use IndexOf, which returns -1 if the item isn't found.
var strings = ["yo", "blah", "foo"];
if (System.Array.IndexOf (strings, "blah") != -1) {
Debug.Log ("Yep.");
}
Or better yet, assuming you're using a recent version of Unity, Array.Contains:
var strings = ["yo", "blah", "foo"];
if (strings.Contains ("blah")) {
Debug.Log ("Yep.");
}
Answer by OWiz · Feb 08, 2013 at 04:03 PM
So make your array of strings and loop through them whilst comparing them to what the user typed. You can compare them with "`==`"
Answer by Kiloblargh · Feb 08, 2013 at 08:25 PM
It's pretty straigtforward and trivial to translate what you wrote into a functioning script if you know anything about scripting at all.
Just off the top of my head:
var cheatStrings : String[];
var testString : String = consoleDisplay.text;
var isValid : System.Boolean = false;
for (var s : int = 0; s < cheatStrings.Length; s++)
{
if (testString == cheatStrings[s])
{
isValid = true;
}
}
if (isValid)
{
Debug.Log "Succeed";
}
else
{
Debug.Log "Failed";
}
So, if something like that didn't just come to you when you thought about the problem, you will have a lot more difficulties ahead of you and before taking on the game you want to make, you need to read and reread the Unity scripting reference, as well as freshen up on programming in general.
But, is this will working fast when i will have about 3000 strings?
Try it and see. The general rule is "Don't worry about performance unless you have to".
I don't know where u got that 'general rule' from but thats so not true. LOL. If I said that at the company I develop for they would laugh at me.
The general rule is not to let performance dictate functionality unless you have to. Developers should never play whisper down the alley with general rules.
This is a late response, but a HashSet might work better than an array. I haven't tested it though, and I'm not sure if the performance impact is significant either way (since this comparison only happens when a console command is run, I assume)
Your answer
![](https://koobas.hobune.stream/wayback/20220613092345im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Where is the directory for GUI skin 0 Answers
Use gui slider to change text field and vice versa? 1 Answer
How to show an array of custom objects in Inspector? 2 Answers
GameObject Array in Editor GUI 3 Answers