btn按钮事件

1.用Delegate 和 Event 来定义一个通用类来处理事件 (观察者模式)

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.UI;

using UnityEngine.EventSystems;

public class NewBehaviourScript : MonoBehaviour, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler

{

    // 定义事件代理

    public delegate void UIEventProxy(GameObject gb);

    // 鼠标点击事件

    public event UIEventProxy OnClick;

    // 鼠标进入事件

    public event UIEventProxy OnMouseEnter;

    // 鼠标滑出事件

    public event UIEventProxy OnMouseExit;

    public void OnPointerClick(PointerEventData eventData)

    {

        if (OnClick != null)

            OnClick(this.gameObject);

    }

    public void OnPointerEnter(PointerEventData eventData)

    {

        if (OnMouseEnter != null)

            OnMouseEnter(this.gameObject);

    }

    public void OnPointerExit(PointerEventData eventData)

{

   if (OnMouseExit != null)

            OnMouseExit(this.gameObject);

    }

}

2.定义btn的操作移动的基本属性:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.UI;

public class btn : MonoBehaviour {

    public float HSpeed;

    public float VSpeed;

    public int  btnName;

    public Transform Objects;

    bool IsWalk=false;

    void Start () {

        Button btn = this.GetComponent<Button> ();

        NewBehaviourScript btnListener = btn.gameObject.AddComponent<NewBehaviourScript>();

        btnListener.OnClick += delegate(GameObject gb) {

            Debug.Log(gb.name + " OnClick");

            IsWalk = true;

        };

        btnListener.OnMouseEnter += delegate(GameObject gb) {

           // Debug.Log(gb.name + " OnMouseEnter");

        };

        btnListener.OnMouseExit += delegate(GameObject gb) {

            Debug.Log(gb.name + " OnMOuseExit");

            IsWalk = false;

        };

    }

    void Update()

    {

        if(IsWalk)

        {

            switch (btnName)

            {

                case 1: Objects.Translate(Vector3.forward * -VSpeed * Time.deltaTime);

                    break;

                case 2: Objects.Translate(Vector3.forward * VSpeed * Time.deltaTime);

                    break;

                case 3: Objects.Rotate(Vector3.up * -HSpeed * Time.deltaTime);

                    break;

                case 4: Objects.Rotate(Vector3.up * HSpeed * Time.deltaTime);

                    break;

                default:

                    break;

            }

        }

        //定义A D W S键盘控制

        float h = Input.GetAxis("Horizontal");

        float v = Input.GetAxis("Vertical");

        //控制旋转左右

        Objects.Rotate(Vector3.up * HSpeed * h * Time.deltaTime);

        //控制前后移动

        Objects.Translate(Vector3.forward * VSpeed * v * Time.deltaTime);

    }

}

注:此代码1为委托事件定义,2是添加在btn上的,按钮持续按下的一种写法,根据事件与监听修改而来,如有雷同或更赞的代码,请评论下方....

猜你喜欢

转载自www.cnblogs.com/XiaoLang0/p/9933122.html
今日推荐