やまめも

【 ゲーム開発・日々のことについて 】

【Unity】onClick : スクリプトから変更 (onClick.AddListener)

例1(問題有の可能性)

//(名前空間の定義)
//using UnityEngine.Events;

if((SituationCreater2.instance.Count) < 10){
	button = ObjectFromToilet.GetComponent<Button> ();
	if (n < 1){
		// ObjectFromToilet.GetComponent<Image>().sprite = null;
	}else if(1 < n && n < 50){
		// ObjectFromToilet.GetComponent<Image>().sprite = ObjFromToiletSprite[0];
		button.onClick.AddListener (() => ButtonItemUnlock());


	}else{
		// ObjectFromToilet.GetComponent<Image>().sprite = ObjFromToiletSprite[1];
		button.onClick.AddListener (() => ButtonItemUnlock());
	}

}

例2

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class ButtonRightLeft : MonoBehaviour {
	public GameObject RightHandle;
	public GameObject LeftHandle;

	Button ButtonRight;
	Button ButtonLeft;

	GameObject FlickManagerObj;
	FlickManager2 FlickManagerScript;

	public static ButtonRightLeft instance = null;
	void Awake () {
		if (instance == null){
			instance = this;
		}
	}
	void Start () {
	}
	void Update () {
	}
	public void AddButtonRightLeft(){
		FlickManagerObj = GameObject.Find("FlickManager").gameObject;
		FlickManagerScript = FlickManagerObj.GetComponent<FlickManager2>();

		ButtonRight = RightHandle.GetComponent<Button> ();
		ButtonLeft = LeftHandle.GetComponent<Button> ();

		ButtonRight.onClick.AddListener (FlickManagerScript.BtnRight);
		ButtonLeft.onClick.AddListener (FlickManagerScript.BtnLeft);

		Debug.Log("Add Listener");
	}
	public void RemoveBtnRightLeft(){
		ButtonRight.onClick.RemoveListener(FlickManagerScript.BtnRight);
		ButtonLeft.onClick.RemoveListener(FlickManagerScript.BtnLeft);

		Debug.Log("Remove Listener");

	}

}


[Unity]uGUIで、ボタンのクリックイベントを自動でセットする。
naochang | 動的にボタンにデータを持った機能を加える