- Home /
How do I create buttons dynamically in OnGui?
I'm trying to create a button for each target. The problem is my code only displays the first 2 buttons - however, I have 6 targets.
Here is my basic code. The _targetList is an array of Vector3 targets (Identified in the start event by scanning the scene for all objects with a certain "enemy" tag). What is causing my buttons to not be shown? Am I using the wrong event? I note that my console is flooded with my debug statements below: but I only need to create these buttons once (I think...)
void OnGUI()
{
//Bottom right group of buttons
print("Group created with " + _targetList.Length.ToString() + " buttons");
GUI.BeginGroup(new Rect(Screen.width - (_targetList.Length * 100), Screen.height - 50, 200, 100));
//Loop through each target
for (int i = 0; i <= _targetList.Length - 1; i++)
{
print("Button " + (i + 1).ToString() + " created: " + new Rect((i * 100), 0, 100, 50).ToString());
//Create a button for each target, loading the attached script with source and target coordinates
if (GUI.Button(new Rect((i * 100), 0, 100, 50), "Shoot Target " + (i + 1).ToString()))
{
StartCoroutine(ShootLaserDynamically(new Vector3(4, 1, 4), _targetList[i]));
}
}
GUI.EndGroup();
}
And you're sure that _targetList.Length is 6, and not 2?
That's the only reason, afaik, why the loop would only run twice. If you collapse your debug-statements in the Unity console, do you get all 6 "Button x created: Rect(x,x,x,x)"? Or just 1 and 2?
Also, i <= _targetList.Length - 1
would be the same as
i < _targetList.Length
if I'm not thinking backwards.
Oh, and yes, you're using the correct function. The buttons need to be drawn every frame, not just once.
Thanks. _targetList is definitely 6 and I definitely get all 6 button created debug statements, but then only 2 buttons show on my screen.
The code you displayed will work as well, I'm just used to using <= in for statements. Any other ideas?
Answer by -hiTo- · Jan 28, 2013 at 03:11 PM
Yes, of course... It's your GUI Group. It's set to be only 200 pixels wide. And when every button is 100 pixels wide, you can only fit 2.
You need to change
GUI.BeginGroup(new Rect(Screen.width - (_targetList.Length * 100), Screen.height - 50, 200, 100));
to
GUI.BeginGroup(new Rect(Screen.width - (_targetList.Length * 100), Screen.height - 50, (_targetList.Length * 100), 100));
That's the one. if you make that an answer, I'll mark it as correct.
Cheers mate!
Also, you should use GUILayout ins$$anonymous$$d. It's easier to center, scale etc your gui elements that way.
Your answer
Follow this Question
Related Questions
Calling functions from OnGUI 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
AddListener to OnPointerDown of Button instead of onClick 4 Answers
How to make game recognise Screen resolution on startup 1 Answer