Author Topic: Multiple buttons in one script  (Read 5339 times)

Harsul

  • Guest
Multiple buttons in one script
« on: June 27, 2012, 04:52:15 PM »
Hello.

I am trying to make multiple buttons on OnClick i just can't get it to work.
I need something like this:
  1. void OnClick()
  2. {
  3.     if(buttonOne is Clicked)
  4.         ....
  5.        
  6.         if(buttonTwo is Clicked)
  7.         ....
  8. }

Or it could be on void Update it doesn't really matter.
But is there anyway to do this?

PhilipC

  • Guest
Re: Multiple buttons in one script
« Reply #1 on: June 27, 2012, 07:12:58 PM »
You would need that one script to be attached to a single object then every button could have the UIForwardEvents script on it which could forward the click event to that one object. From there UICamera has a couple options for telling you what was clicked. lastHit will give you more detailed information about what was clicked as it returns a RayCastHit or your can look at the hoverObject which is the GameObject the mouse is over.

JRoch

  • Full Member
  • ***
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 140
    • View Profile
Re: Multiple buttons in one script
« Reply #2 on: June 27, 2012, 08:04:31 PM »
Alternatively, just attach one script to every button object, which examines the button press event against the calling gameobject.name property.  Below I use OnPress, but you could use any NGUI event similarly.

For example:

public class GeneralUIButtonHandler : MonoBehaviour {

    //
    //  Simply handles button events and does the appropriate actions
    //

    void OnPress(bool isDown)
    {
        // return without doing anything if this is a button up event
        if (!isDown) return;

        // don't trigger buttons if the mouse click isn't a left mouse button event
        if (UICamera.currentTouchID != -1) return;

        // do actions based upon the name of the gameobject
        if (this.gameObject.name == "Button_1")
        {
            // do something here
        }
        else if (this.gameObject.name == "Button_2")
        {
            // do something else here
        }
    }
}


Granted, you'd probably not want to use this for dozens and dozens of buttons, but for just a few it'll work just fine and the comparison evaluations shouldn't be much of a hit since it's local object data with a string compare.
« Last Edit: June 27, 2012, 08:10:32 PM by JRoch »

Nicki

  • Global Moderator
  • Hero Member
  • *****
  • Thank You
  • -Given: 33
  • -Receive: 141
  • Posts: 1,768
    • View Profile
Re: Multiple buttons in one script
« Reply #3 on: June 28, 2012, 03:25:03 AM »
Use a UIButtonMessage and send a "Button1Clicked" or "Button2Clicked" (etc) to the helper object of your choice. Have your helper object have a script (component) with  void Button1Clicked() {} and void Button2Clicked() [} defined. Release the game and make tons of $$. :D