UGUI如何在程序中动态的为按钮绑定方法

需要用到两个脚本:


UGUI如何在程序中动态的为按钮绑定方法_第1张图片



EventTriggerListener .cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

/// 
/// hunk xu
/// 
public class EventTriggerListener : EventTrigger
{
    public delegate void VoidDelegate(GameObject go);
    public VoidDelegate onClick;
    public VoidDelegate onDown;
    public VoidDelegate onEnter;
    public VoidDelegate onExit;
    public VoidDelegate onUp;
    public VoidDelegate onSelect;
    public VoidDelegate onUpdateSelect;

    static public EventTriggerListener Get(GameObject go)
    {
        EventTriggerListener listener = go.GetComponent();
        if (listener == null) listener = go.AddComponent();
        return listener;
    }
    public override void OnPointerClick(PointerEventData eventData)
    {
        if (onClick != null) onClick(gameObject);
    }
    public override void OnPointerDown(PointerEventData eventData)
    {
        if (onDown != null) onDown(gameObject);
    }
    public override void OnPointerEnter(PointerEventData eventData)
    {
        if (onEnter != null) onEnter(gameObject);
    }
    public override void OnPointerExit(PointerEventData eventData)
    {
        if (onExit != null) onExit(gameObject);
    }
    public override void OnPointerUp(PointerEventData eventData)
    {
        if (onUp != null) onUp(gameObject);
    }
    public override void OnSelect(BaseEventData eventData)
    {
        if (onSelect != null) onSelect(gameObject);
    }
    public override void OnUpdateSelected(BaseEventData eventData)
    {
        if (onUpdateSelect != null) onUpdateSelect(gameObject);
    }
}


UIMain .cs

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class UIMain : MonoBehaviour
{
    public Button Btn01;
    public Button Btn02;


    void Start()
    {
        if (Btn01 != null)
            EventTriggerListener.Get(Btn01.gameObject).onClick = OnButtonClick;
        if (Btn02 != null)
            EventTriggerListener.Get(Btn02.gameObject).onClick = OnButtonClick;
    }
    private void OnButtonClick(GameObject go)
    {

        if (go == Btn01.gameObject) {
            print ("您点击的是btn01");

        } else if (go == Btn02.gameObject) {
            print ("您点击的是btn02");
        }
    }


j将Uimain挂到场景中
UGUI如何在程序中动态的为按钮绑定方法_第2张图片


UGUI如何在程序中动态的为按钮绑定方法_第3张图片



FR:海涛高软(hunk Xu) QQ技术交流群:386476712

你可能感兴趣的:(UGUI)