- 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')
Variants show how to load a numbered level upon clicking a button:
Also check this Q&A for how to remove listeners and more.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
No comments:
Post a Comment