Skip to content

Instantly share code, notes, and snippets.

@tsubaki tsubaki/ButtonAction.cs
Last active Aug 29, 2015

Embed
What would you like to do?
ボタンのイベントをスクリプト上で登録する
using UnityEngine;
using UnityEngine.UI;
[ExecuteInEditMode]
public class ButtonAction : MonoBehaviour
{
#if UNITY_EDITOR
[SerializeField, HideInInspector]
Button button;
void Reset ()
{
// シーン内からボタンを取得する.
button = GameObject.Find ("/Canvas/Button").GetComponent<Button> ();
// 既にボタンにイベントを登録していたら削除する.
UnityEditor.Events.UnityEventTools.RemovePersistentListener<GameObject> (button.onClick, OnClick);
// ボタンにイベントを登録する.
UnityEditor.Events.UnityEventTools.AddObjectPersistentListener<GameObject> (button.onClick, OnClick, gameObject);
}
void OnDestroy ()
{
// ボタンからイベントを削除する.
UnityEditor.Events.UnityEventTools.RemovePersistentListener<GameObject> (button.onClick, OnClick);
}
#endif
// クリック時にイベント登録したオブジェクト名を表示する.
void OnClick (GameObject obj)
{
Debug.Log (gameObject.name);
}
}
@tsubaki

This comment has been minimized.

Copy link
Owner Author

tsubaki commented May 31, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.