How can I generate and setup buttons via code
In my RPG there characters with different abilities. Assuming I have an array of abilities for a character I want to generate a menu with the same number of buttons as the number of skills in the array. My current approach is to call a function onCommand(int index) where I specify the index in the editor when a button is pressed and use that to detect which command was used. How can I do this via code?
Or Is there another method to achieve the same effect? Should I use a dropdown menu(never used them) for this or make a menu Prefab for each character and call it a day?
Answer by Pinkuboxu · Jun 02, 2018 at 06:54 PM
Maybe look into the other gui elements you say you haven't used before and see how they work? There isn't a single objective way, you have to use whatever feels best to you. This is how innovation happens! You can learn to create buttons in script here. This is sort of an old, but not wrong, way to do it.
I think with the more recent(not really recent) GUI design system they implemented in Unity, the workflow is to build the gui in the editor visually, make it a prefab, then referencing the instance of the prefab in your logic. I'm assuming that the characters have the same amount of abilities as each other since you said you were using an Array and not a List. If the characters have different amounts of abilities from each other then you will want to use a list. If that is the case then you might like doing it the old way. If they all have the same amout of abilities, you can add the button components you need manually and then use their OnClick events on their component in the inspector to point to any public methods you've made on the character class script. Even if the characters have variant amounts of abilities, you could just disable the buttons that aren't used for that character from your script. Use a Vertical Layout Group to line your buttons up together, btw.
Your answer
Follow this Question
Related Questions
UI Button OnClick Only Works the First Time 2 Answers
unity 2018.3.12f1 Button OnClick call function on another instance? of script 0 Answers
How to make button click continuous ? 0 Answers
With the new unity input system. How do I setup UI buttons like in the old system. 0 Answers
UI Buttons without blocking raycast 0 Answers