- Home /
Is it possible to create a button dynamically?
Hello, I'm creating a function that will be used to add names to a list. Multiple names can be added and the names will be displayed on buttons so the user can interact with them. I know how to make it all work but instead creating a certain number of buttons at the start of the level, is it possible to create a button dynamically as needed? thanks
Answer by save · Sep 26, 2011 at 03:02 PM
Yes it's fully possible! The solution depends on if you're doing a button in the GUI or the scene.
In the GUI throw it into a for-loop where you check how many input-lines is available. Then offset it each iteration.
In the scene you can instantiate an object that has a OnMouseDown-function.
Awesome! I was just about to try that, but how would i access each button? I'm using GUI btw.
var yourNamesList:Array=new Array(String);//populate this with your names as you described.
var toolbarSelected:int=-1;
//Either with a toolbar:
toolbarSelected=GUI.Toolbar(Rect(0,0,Screen.width,Screen.height),toolbarSelected,yourNamesList.ToBuiltin(String));
//Or splotch them down manually:
for(var i:int=0;i < yourNamesList.length;i++)GUI.button(Rect(0,i*20,20,10),yourNamesList[i]);
@blitzen I used your "for" method and it creates the buttons like a charm. How could I run a function from one of the newly created button? example: if (GUI.Button(Rect(0,i*20,20,10),yourNamesList[i])){ GetName(yourNamesList[i]); } thanks
@ThumbStorm: That's exactly how you'd do it; you just answered your own question.
Your answer
Follow this Question
Related Questions
GUI.Label positioning for many device resolutions 1 Answer
How can I dynamically create scene ? 1 Answer
GUI, making main page lead into an instructions page 2 Answers
How to get Rect from scene Button ? 1 Answer
Unity 5 GUI system 1 Answer