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*));*

}
}
GUI.EndGroup();
}

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));