Author Topic: Dynamic buttons--how to change function called when clicked?  (Read 1472 times)

Deozaan

  • Newbie
  • *
  • Thank You
  • -Given: 44
  • -Receive: 4
  • Posts: 42
    • View Profile
    • Deozaan.com
Dynamic buttons--how to change function called when clicked?
« on: March 05, 2014, 12:22:58 PM »
Hi folks,

Over the past couple of days I've been looking over the NGUI documentation, forum threads, video tutorials, and more trying to figure this out. I've come to the conclusion that I just need to ask because I can't find the answer anywhere else. (I'm not saying the answer isn't out there, just that I seem to be unable to find it!)

I would like to dynamically instantiate an unknown number of buttons at runtime that each correspond to an action or skill, depending on the character.

For example, if my Fighter class has 5 actions and my Mage class has 8 actions, then if I select a fighter character I'll want to instantiate 5 buttons, each one mapped to a different action. If I select a Mage character, then I'll want to instantiate 8 buttons, each one mapped to a different action.

The part I'm having trouble figuring out (though I'll gladly accept hints/tips/help with any of it) is how would I dynamically change the function that is called when the button is clicked? I mean, how do I dynamically map a button to a different skill/action?

Or am I thinking about this the wrong way?

Nicki

  • Global Moderator
  • Hero Member
  • *****
  • Thank You
  • -Given: 33
  • -Receive: 141
  • Posts: 1,768
    • View Profile
Re: Dynamic buttons--how to change function called when clicked?
« Reply #1 on: March 05, 2014, 02:28:36 PM »
There are many ways to do it.

One way would be to have a CharacterButtonController class and inherit from that so you have a MageButtonController, FigherButtonController etc.

The Controllers should then instantiate their buttons depending on however many they need, and attach a listener at that time.
Pseudocode:
  1. class MageButtonController : CharacterButtonController{
  2. public GameObject buttonPrefab;
  3. void InitializerMethod(){
  4. var button1 = Instantiate<GameObject>(ButtonPrefab);
  5. UIEventLIstener.Get(button1).onClick += Button1Method;
  6. }
  7.  
  8. void Button1Method(){
  9. Debug.Log("The first button was clicked!");
  10. }
  11. }
  12.  
  13.  
  14.