Unity 自定義事件 AddListerner

Unity 自定義事件 AddListerner

Unity中有的Button組件有onCick.AddListener屬性,如果想要自己定義事件並能夠像Button一樣AddListener使用需要怎麼做呢?
Unity中提供有UnityEvent類來用作事件的聲明,下面直接放上代碼,再一一說明。

CustomEventClass.cs

/* 事件類型的聲明類 */
using UnityEngine.Events;
using UnityEngine;

// 開始移動事件
public class StartMoveEvent : UnityEvent<GameObject, string> {}

// 移動中事件
public class OnMoveEvent : UnityEvent<GameObject, string> {}

// 移動結束事件
public class EndMoveEvent : UnityEvent<GameObject, string> {}

這個類主要是聲明幾個自定義的事件,可以按照個人喜好和代碼風格來確定放在一個腳本或者是跟邏輯腳本放在一起。
自定義的類繼承了 UnityEvent 就成爲了一個Unity的事件,支持多參數,但至多隻能是4個,具體API可以看 UnityEvent.cs 文件。

TestGameObject.cs

/* 測試的Mono類 */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestGameObject : MonoBehaviour {

	public StartMoveEvent startMoveEvent = new StartMoveEvent();
	public OnMoveEvent onMoveEvent = new OnMoveEvent();
	public EndMoveEvent endMoveEvent = new EndMoveEvent();

	static float startTime = 0f;

	void Awake(){
		startMoveEvent.AddListener((GameObject go, string str) => {
			Debug.Log("<color=yellow>Start Move, GameObject is -> " + "  string content is -> " + str + "</color>");
		});
		onMoveEvent.AddListener((GameObject go, string str) => {
			Debug.Log("<color=orange>On Move, GameObject is -> " + "  string content is -> " + str + "</color>");
		});
		endMoveEvent.AddListener((GameObject go, string str) => {
			Debug.Log("<color=green>End Move, GameObject is -> " + gameObject.name + "  string content is -> " + str + "</color>");
		});
	}

	void Start(){
		StartCoroutine(_CubeMove());
	}

	IEnumerator _CubeMove(){
		startMoveEvent.Invoke(gameObject, "開始移動");
		startTime = Time.time;
		while (Time.time - startTime < 2f)
		{
			transform.position += new Vector3(0.03f, 0, 0);
			yield return null;
			onMoveEvent.Invoke(gameObject, "移動中");
		}
		endMoveEvent.Invoke(gameObject, "移動結束");
	}
}

這個類是測試事件的類,用協程寫了一個簡單地移動。
同樣的,在Awake中添加事件,參數也是和定義的事件類相匹配的。xxx.Invoke()是執行事件,因爲是自定義的事件,具體執行的邏輯不通,需要在相應的地方執行。

接下來看下具體的效果(只是在對應時間輸日誌):
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章