- Home /
Not updating value in foreach loop OnGUI()
I can't get some a List to update inside a foreach loop inside a GUI.Button call. The actual value is correct using Debug.Log(value) but not on the GUI
Code:
foreach (var element in categoriesArray)
{
if ( !element.Toggled )
{
if ( GUI.Button(new Rect(15,185,170,185), element.ToggledString ) )
{
Debug.Log("pressed on");
element.Toggled = true;
element.ToggledString = "[X]";
Debug.Log(element.ToggledString);
}
}
else if ( element.Toggled )
{
if ( GUI.Button(new Rect(15,185,170,185), element.ToggledString ) )
{
element.Toggled = false;
element.ToggledString = "[ ]";
Debug.Log("pressed off");
Debug.Log(element.ToggledString);
}
}
}
Any good reason you're not using UI? Unless you're editor scripting, you should be using the newer UI system.
I don't understand the language of your question, but the only thing I spy "wrong" with this code is that it could be about 15 lines shorter and achieve the same thing. Also, if you're making a list of buttons, shouldn't their x or y position involve a for-loop's iterator?
Oh wait, I get the question now. The element's text is not updated to reflect the change to element.ToggledString, right? Okay, I couldn't figure it out in 5 seconds, so I'll publish the question.
I prefer script UI to be honest. Yeah the element's text is not updated visually but doing a Debug.Log(value) prints the updated value.
You are going through each element in categoriesArray and drawing all of them in the same rect (15,185,170,185). Have you tested if some of the GUI is changing but you can't see it since even one "[X]" in the array might cover all elements with "[ ]"?
edit: yeah, like @maccabbe says, and I mentioned earlier, "if you're making a list of buttons, shouldn't their x or y position involve a for-loop's iterator?"
All I can think of is that the change wouldn't happen until the next frame. If it doesn't happen at all, perhaps some code we aren't seeing is responsible.
You could compress this down into a single button. Not saying it will help, but it is cleaner. It's conceivable that your conditionals are to blame for this, but I'll admit it seems unlikely.
if (GUI.Button(new Rect(15,185,170,185), element.ToggledString )) {
element.Toggled = !element.Toggled;
element.ToggledString = (element.Toggled) ? "[X]" : "[ ]";
}
It was because I rendered it over the same pos over and over again. I only made a non for loop pos for testing.
Thanks
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# - foreach problem 3 Answers
Failure to destroy a game object in a for each loop 1 Answer