兩種於 Unity3d C# 中進行 EventHandler 的編碼方式.

兩種於 Unity3d C# 中進行 EventHandler 的編碼方式.

example : 程式建構

  • MyEventPackage 為 Event 封包.
  • MyObject 每 3 個循環進行一次 Event Dispatch.
  • MyListener 於接收到事件後進行 Debug.Log 寫入.

For Dispatch Side :

[csharp]public class MyEventPackage

{
public string MyData{ get; private set; }
public MyEventPackage( string _data ) : this()
{
this.MyData = _data;
}
public MyEventPackage()
{
this.MyData = null;
}
}

public class MyObject : MonoBehaviour
{
public event EventHandler MyEvent;
private int cnt;
void Start()
{
cnt=0;
}
void Update()
{
if( cnt>=3 )
{
cnt=0;
if( MyEvent != null )
{
// when someone listening, kick their ass to move.
MyEvent( this, _EventSocket );
}
}
else
{
cnt++;
}
}
}[/csharp]

For Listener Side :

第一種

[csharp]public class MyListener : MonoBehaviour

{
// the object to listening, setup in Editor
public MyObject MyLittleObject;

public void Start()
{
MyLittleObject.MyEvent += (sender, e) {
// when every time MyLittleObject dispatch event
// run following coding…
MyEventPackage _tmp = (MyEventPackage) e;
Debug.Log("Event received : "+ _tmp.MyData.ToString() );
}
}
}[/csharp]

這種的好處是簡短清楚, 缺點是不能刪除 Listener. (有方法嗎)

第二種

[csharp]public class MyListener : MonoBehaviour
{
// the object to listening, setup in Editor
public MyObject MyLittleObject;

public void StartListening()
{ // start listening to object
MyLittleObject.MyEvent += HandlerMyEvent;
}
public void StopListening()
{ // stop listening.
MyLittleObject.MyEvent -= HandlerMyEvent;
}
private void HandlerMyEvent(object sender, EventArgs e)
{
// when every time MyLittleObject dispatch event
// run following coding…
MyEventPackage _tmp = (MyEventPackage) e;
Debug.Log("Event received : "+ _tmp.MyData.ToString() );
}
}[/csharp]

這種的好處是甚麼功能也標示清楚, 也可以進行 Listener 刪除,
缺點就是太繁覆了, trace code 有點麻煩.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

*

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料