- Home /
How to manipulate two buttons with one for loop C#
Hi everyone, can you manipulate two buttons with one for loop? From what it looks like I can only use a for loop once and then you will have to create another for loop for the second button.Otherwise I get an error i does not exist in it's current context.
[System.Serializable]
public class ButtonValue
{
public int IntValue = 0;
}
public List<ButtonValue> Buttons = new<ButtonValue>(4);
Void OnGUI(){
for (int i = 0; i < Buttons.Count i++)
if(GUILayout.Button("Button1"GUILayout.Width(125), GUILayout.Height(25)){
++Buttons[i]
}
//error i does not exist in it's current context
if(GUILayout.Button("Button2"GUILayout.Width(125), GUILayout.Height(25)){
++Buttons[i]
}
}
I don't want to sound too rude....your code sample is a complete train wreck. Seriously. There are like 15 separate errors in there, and I know you know how to do this stuff. Fix it!
Did that come across rude? It felt rude. Apologies in advance. Or rather in arrears.
I'm not getting any errors from the console.Could you please be a bit more specific?
Sure, I'll list the first five here:
1) You have a closing brace immediately after your first declaration (public int...), ending the class. There should be no brace there.
2) public List Buttons = new(4); -- needs to have "List" -- as in "new List..."
3) "for (int i = 0; i < Buttons.Count i++)" -- needs to have a semi-colon after "Count"
4 and 5) "if(GUILayout.Button("Button1"GUILayout.Width(125), GUILayout.Height(25)){" -- needs to have a comma after "Button1". Also needs an extra right paren at the end, before the brace.
6) "++Buttons[i]" needs a semi-colon after it
...and there are more. If you copy and paste the code from your question into a new c# file, you should see all of these errors (well, one at a time as you fix them). I wonder if it's a problem with the way you're copying and pasting your code here?
Answer by MarkFinn · Sep 29, 2012 at 03:45 AM
You need to be sure that the code using the variable i is inside the for block.
Start by adding a { to the end of the line
for (int i = 0; i < Buttons.Count i++)
otherwise only the first statement after it is in the for loop.
Your answer

Follow this Question
Related Questions
C# SphereCast isn't Inaccurate 1 Answer
C# GameObject is not detecting collision with Character Controller 2 Answers
FPS keep a loadout 0 Answers
Converting C# Controller from WASD Controls to Click-Based 1 Answer
C# GUI.Tooltip If Statement 2 Answers