unity button用法

xiaoxiao2025-04-17  10

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 }

 

转载请注明原文地址: https://www.6miu.com/read-5028499.html

最新回复(0)