UNITY之EventTrigger,EventListener

UIEventListener.cs 对一些常用的事件进行了封装和继承。

  一,常用事件:
  void OnClick ():点击事件;

  void OnDoubleClick ():二次或多次点击事件

  void OnHover (bool isOver):手指覆盖事件;

  void OnPress (bool isPressed):手指点击事件,包含按下、抬起;isPressed为按下,false为抬起;

  void OnSelect (bool selected):是否被选择;

  void OnDrag (Vector2 delta):手指滑动事件;

  void OnKey (KeyCode key):“键”事件;

  二,实质:

  这些监听事件都是建立在委托事件上:

  publicdelegatevoid BoolDelegate (GameObject go, bool state);

  public BoolDelegate onPress;

  三,前提条件:

  UIEventListener的GameObejct包含Colllider;

  四,怎使用:

  1,静态关联方法:

  UIEventListener.Get(GameObject).OnPress += pressList;

  2,直接重写:

  脚本所在的GameObject包含Colllider,直接重写监听事件:

  publicclass SceneTwo : MonoBehaviour {

  void OnPress (bool pressed)

  {

  Debug.Log(“OnPress ”+enabled+“   ”+NGUITools.GetActive(gameObject)+“   ”+pressed);

  if (enabled && NGUITools.GetActive(gameObject))

  {

  }

  }

  void OnDrag (Vector2 delta)

  {

  Debug.Log(“OnDrag ”+enabled+“   ”+NGUITools.GetActive(gameObject)+“   ”+delta);

  if (enabled && NGUITools.GetActive(gameObject))

  {

  }

  }
 }

//Demo1

using UnityEngine;
using System.Collections;

public class EventTriggerTest : MonoBehaviour {


    public  GameObject button;

    // Use this for initialization
    void Start () {
    
        UIEventTrigger ue = button.AddComponent <UIEventTrigger> ();
        ue.onRelease.Add (new EventDelegate (this, "ReleasedButton"));
        ue.onPress.Add (new EventDelegate (this,"PressButton"));
        ue.onClick.Add(new EventDelegate(this,"MyClick") );

        ue.onPress [0].parameters [0] = new EventDelegate.Parameter ();
        ue.onPress [0].parameters [0].obj = button;
        ue.onClick [0].parameters [0] = new EventDelegate.Parameter ();
        ue.onClick [0].parameters [0].obj = button;

    }
    
    // Update is called once per frame
    void Update () {
    
    }

    void MyClick(GameObject obj){
        print (obj.name+" : "+"click");
    }

    void PressButton(GameObject obj){
    
        print (obj.name+" : "+"pressButton");
    }

    void ReleasedButton(GameObject  obj){
    
        print (obj.name+" : "+"ReleasedButton");
    }
}

//Demo2


public class EventListener : MonoBehaviour {


    // Use this for initialization
    void Start () {


        foreach (Transform item in transform ){
            UIEventListener.Get (item .gameObject ).onClick = MyClick;
        }
    }
    
    // Update is called once per frame
    void Update () {
    
    }

    void MyClick(GameObject obj){
        print (obj.name+" : "+"click");
    }

}

猜你喜欢

转载自blog.csdn.net/qq_39887964/article/details/79630827