- Home /
Can I dynamically create buttons from an arraylist?
In my program I am trying to create buttons from an arraylist; however, I can't seem to get it working. The button is displayed with the correct name whenever I add something to the arraylist useroptions, but whenever I click on the button the action that I define in the curly braces is not triggered. I have the following code in my OnGUI function:
foreach (string s in userOptions)
{
Debug.Log(s);
if (GUI.Button(new Rect(100, 100, 300, 300), s))
{
Debug.Log ("HERE");
npcConversation.reponseText = s;
}
}
Answer by robertbu · Jun 27, 2013 at 05:36 AM
I ran a quick test of your code. It appears to work fine (other than you are placing all the buttons on top of each other). Here is what I did:
using UnityEngine;
using System.Collections;
public class Bug20 : MonoBehaviour
{
string[] userOptions = new string[] {"one", "two", "three"};
void OnGUI ()
{
foreach (string s in userOptions)
{
Debug.Log(s);
if (GUI.Button(new Rect(100, 100, 300, 300), s))
{
Debug.Log (s);
}
}
}
}
If I click on the button, it outputs text for all three buttons (which I did not expect).
I'ts probably because they are on top of each other like you said.
So maybe when you click, all of them get clicked.
You might wanna make your Rect with a dynamic vars so the buttons wont be on top of each other.
@robertbu I assume the first Debug.Log is a typo? That code should print out all the button texts even if you don't push the button, I think?
@techboysquared1 I assume by "not triggered" you are checking via the log, so we can safely ignore any possible bug with the responseText logic?
Since you'll be spitting out a hell of a lot of logs, are you certain you didn't just miss the one that said "HERE" in the sea of other logs?
On a side note: As the others have mentioned, your code will put all your buttons in the same place. While you could mess with the Rect, you could also use GUILayout and get Unity to figure it out for you.
Yes. I knew that it would stack them on top of each other. I was only had one button while i was messing with this, so I didn't code it to change button location. Also, I have found my problem apparently it was something to do with the button being stacked on top of a textarea. I moved it off of the text area and everything is fine now.
How odd that stacking buttons on top lets them all trigger, but a textarea doesn't allow clicks to go through. The wonders of Unity! Thanks for revealing the true cause ;)
I still recommend taking a look at the GUILayout class though, could save you lots of time messing around with Rects.
Edit: $$anonymous$$ight be worth turning that into an answer, btw. That way anyone with a similar problem can quickly see what fixed it for you.
I just realized how horrible my grammar was in that comment. I guess it's because it's 4 A$$anonymous$$, and I'm looking at the GUILayout now.