- Home /
Array strings/Loops problem
HI everyone, I've a problem, why Unity do not recognize all strings of my array or just the last.... Here is my code :`
var cheatField : String = "Cheat code";
var cheatCodes : String[];
if (GUI.Button(Rect(Screen.width - Screen.width, Screen.height - 60, 250, 20), "Try debugging")) {
for (var i : int = 0; i < cheatCodes.Length; i++) {
//for (var code : String in cheatCodes) {
if (cheatField == cheatCodes[i]) {
msgInfos = "Code recognized";
}
if (cheatField != cheatCodes[i]) {
msgInfos = "Error : unknown code !";
}
}`
thanks for advance
Answer by Fornoreason1000 · May 23, 2014 at 12:02 PM
what happening your code is running for each cheat code inside you list, try debugging you msgInfos and both of them came up regardless...the problem was that even after you found a match or an error, your looping code would continue to run causing you problems, Unity reconied all your strings all along, its was just made hard due to a tiny logical mistake
#pragma strict
var cheatField : String = "Cheat code";
var cheatCodes : String[];
var msgInfos : String;
function OnGUI() {
if (GUI.Button(Rect(Screen.width - Screen.width, Screen.height - 60, 250, 20), "Try debugging")) {
var match = false;
for (var i : int = 0; i < cheatCodes.Length; i++) {
//for (var code : String in cheatCodes) {
if (cheatField.ToUpper() == cheatCodes[i].ToUpper()) {
match = true;
msgInfos = "Code recognized";
Debug.Log(msgInfos);
}
}
if (match == false) {
msgInfos = "Error : unknown code !";
Debug.Log(msgInfos);
}
match = false;
}
}
I have edited your code, my Unity Script is poorly formatted i apologies. to fix your issue, i moved your Error Message outside of the loop then i changed the condition to check for a bool called watches was false, i then set it to true whenever a reconised string was put through and done!
Debug.Log is a very useful function and lets you know everything that goes on if you use it right
Hope it helps
Thanks Fornoreason1000 for your great answer, now I understand. $$anonymous$$y script was for creating GUI Textfield for in game cheat codes. I hope also that this question help others unity developpers. Thabks again for all.
Answer by Asteiros · May 23, 2014 at 12:06 PM
You are setting value msgInfos in a loop. As a result you'll get "Code recognized" if last one is "Cheat code" else "Error...". Use msgInfos += "Code recognized\n".
Your answer
Follow this Question
Related Questions
Using LINQ within a foreach only runs once 1 Answer
how do I scroll thru a array 2 Answers
How to split a string into array? 2 Answers
public string array controlled by an int in the inspector 1 Answer