unity button用法
1.MonoBehaviour 接扣事件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class ButtonGai : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
public void OnPointerDown(PointerEventData eventData)
{
//滑鼠按下事件
}
public void OnPointerUp(PointerEventData eventData)
{
//滑鼠擡起事件
}
}
2.圖片切換
public Button btn;
public Sprite downSprite;
btn.GetComponent<Image>().sprite = downSprite;
3.滑鼠點選事件
void Start () {
Button btn = this.GetComponent<Button> ();
btn.onClick.AddListener (OnClick);
}
private void OnClick(){
Debug.Log ("Button Clicked. ClickHandler.");
}
注意:
1.這個 AddListener 每次呼叫都會新增一個監聽,不能放在UpDate裡;
2.如果指令碼是 DontDestroyOnLoad 的,記得在 AddListener 之前加上 button.onClick.RemoveAllListeners();
3.如果不想清空按鈕所有事件(雖然很少這麼做),你可以用 button.onClick.RemoveListener(btnAction);來移除指定事件;
private GameObject buttonObj; 9 private void Start() 10 { 11 buttonObj = GameObject.Find("Button"); 12 buttonObj.GetComponent<Button>().onClick.AddListener(M); 13 buttonObj.GetComponent<Button>().onClick.AddListener(F); 14 } 15 void M() 16 { 17 print("執行了M方法!"); 18 } 19 public void F() 20 { 21 print("執行了N方法!"); 22 }