Sunday, 28 February 2016

Programmatically handling button clicks

Since Unity 5 we have buttons that the designer can hard-wire to component (no-arg) functions. Usually this may be a good thing. But not always.

  • Sometimes you want to bind a button dynamically.
  • Or you may want to pass a parameter to the target function
  • Or just add code to a button.
A handy script allowing you to bind a button to a message dynamically. By default the message is delivered to the named object, this can be customised for delivering to children or ancestors. If no object name is specified, delivery uses the button object as a starting point (useful to implicitly deliver upwards to a 'panel controller')

using UnityEngine;
using UnityEngine.UI;
public class MessageAction : MonoBehaviour {
public enum MessageMode{UPWARDS, SELF, CHILDREN};
public MessageMode mode = MessageMode.SELF;
public string objectName;
public string message;
void Start () {
Button button = GetComponent<Button> ();
button.onClick.AddListener (DoSendMessage);
}
private void DoSendMessage(){
GameObject target = this.gameObject;
if (objectName.Length > 0) {
target = GameObject.Find (objectName);
}
switch (mode) {
case MessageMode.SELF:
target.SendMessage (message);
break;
case MessageMode.CHILDREN:
target.BroadcastMessage (message);
break;
case MessageMode.UPWARDS:
target.SendMessageUpwards (message);
break;
}
}
}

Variants show how to load a numbered level upon clicking a button:

using UnityEngine;
using UnityEngine.UI;
public class LoadLevelButtonAction : MonoBehaviour {
public int level = -1;
public string name;
void Start () {
Button button = GetComponent<Button> ();
button.onClick.AddListener (Apply);
}
void Apply(){
if (level > -1) {
Application.LoadLevel (level);
} else {
Application.LoadLevel (name);
}
}
}
using UnityEngine;
using UnityEngine.UI;
public class LoadLevelButtonAction2 : MonoBehaviour {
public int level = -1;
public string name;
void Start () {
Button button = GetComponent<Button> ();
button.onClick.AddListener (
() => {
if (level > -1) {
Application.LoadLevel (level);
} else {
Application.LoadLevel (name);
}
}
);
}
}

Also check this Q&A for how to remove listeners and more.

No comments:

Post a Comment