會用Event的情況通常是我在和其他SDK等做整合時,都已經有那些SDK準備好的Event可直接註冊使用,因此不需要了解那些Event是怎麼生成的;而這邊記錄的是完全無中生有,包含Event的生成、註冊和使用,這樣以後就可以在自己的程式自己來了。
以下是簡單的創造一個Event並來使用:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class ZZZ : MonoBehaviour
{
class TypeEventArgs : EventArgs
{
public float x = 0;
public float y = 0;
}
private event EventHandler eventHandler;
private TypeEventArgs tempEventArgs = new TypeEventArgs();
void Start()
{
this.eventHandler += ReceiveData;
}
void Update()
{
tempEventArgs.x += Time.deltaTime;
tempEventArgs.y += 2 * Time.deltaTime;
eventHandler(this, tempEventArgs);
}
public void ReceiveData(System.Object sender, EventArgs e)
{
Debug.Log(Mathf.FloorToInt((e as TypeEventArgs).x) + " = " + Mathf.FloorToInt((e as TypeEventArgs).y));
}
}
我做了一個Event,然後觸發此Event的情況是每個Frame時,會顯示一個累加時間和其兩倍的時間值。因此觸發條件便可因應各種需要,例如點擊一個按鈕時、用USB連接的Arduino傳過來資料時、或是有預料之中的錯誤發生時等。就可用Event的形式來加以對應。
沒有留言:
張貼留言