1. 程式人生 > >btn按鈕事件

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上的,按鈕持續按下的一種寫法,根據事件與監聽修改而來,如有雷同或更讚的程式碼,請評論下方....