GUI problem: Lack of Events and Listeners.

I have a screen (Empty GameObject) with three buttons (child GameObjects with GUITexture + Script) on my scene. What is an good approach when dealing with buttons? I want to know what button the user clicked without having to add a reference to the Screen in the button class. I am used to Actionscript 3 where you add listeners and dispatch events. Any tips?

- Screen
  |- Button1
  |- Button2
  |- Button3

I’m a little confused because I’m not sure why you want to reference the Screen class, but you can make an event based system.

You have a little bit of choice if you want a global button manager or events fired by individual buttons. Here’s an individual button system:

using System;
using UnityEngine;

public class Button : MonoBehaviour {
    private GUITexture thisTex;
    //Cache a reference to the button.

    public event Action onClick;
    //Action is a generic delegate in the System namespace.

    void Start () {
        thisTex = guiTexture;
        StartCoroutine( ListenForButton() );
    }

    //Here's a performance trick.  Checking for Input in an infinite coroutine will help performance.
    //Update() is called via reflection slowing it down some.
    //And we aren't allocating any additional memory in the loop.
    private IEnumerator ListenForButton() {
        for (;;) {
             if(thisTex.HitTest(Input.mousePosition) && Input.GetMouseButtonDown(0) ) {
                  if(onClick != null) 
                      onClick();
             }
             yield return null;
        }
    }
}

Example:

   someButtonScript.onClick += buttonListen.SomeMethod();

Now if you want to get fancier, you can write an extension method that gets the event by referencing the guiTexture.

using System;
using UnityEngine;

public static class ExtensionMethods {
      public static void AddListener (this GUITexture guiTex, Action listener) {
             var buttonScript = guiTex.GetComponent<Button>();
             if(buttonScript != null)
                    buttonScript.onClick += listener;
             else
                    Debug.Log("There is no Button script attached to the Game Object");
    }
}

And then you can access it like such:

 var guiTex = (GUITexture)FindObjectOfType(GUITexture);
 guiTex.AddListener( someScript.Method() );