GF内置事件订阅
因为gf全是异步加载,其内置了这一套事件,常见的异步功能都有自己的事件。
例如:内置UI事件,直接使用gf的event组件,使用对应的事件id即可。 GameEntry.Event.Subscribe(OpenUIFormSuccessEventArgs.EventId, OnOpenUISuccess)
uiform中使用事件,可以在open和close进行生命周期管理,并且可以通过判断userdata的方式,查看是否是此脚本发出的事件
private void OnWebRequestSuccess(object sender, GameEventArgs e)
{
WebRequestSuccessEventArgs ne = (WebRequestSuccessEventArgs)e;
if (ne.UserData != this)
return;
Log.Debug("wtf:{0}",ne.WebRequestUri);
}
GF自定义事件
1、创建事件类
需要创建一个事件类,继承GameEventArgs,其中可以保存自己需要发送的数据,例如下面的EventName
using GameFramework.Event;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GameFramework;
namespace StarForce
{
public class TestEvent : GameEventArgs
{
public static readonly int EventId = typeof(TestEvent).GetHashCode();
public override int Id
{
get
{
return EventId;
}
}
public string EventName
{
get;
private set;
}
public static TestEvent Create(string name)
{
TestEvent testEvent = ReferencePool.Acquire<TestEvent>();
testEvent.EventName = name;
return testEvent;
}
public override void Clear()
{
EventName = null;
}
}
}
2、触发事件
在需要执行事件的地方,使用EventComponent组件的Fire方法,后面的参数决定了执行哪一类事件
GameEntry.Event.Fire(this, TestEvent.Create("Hello,我的第一个自定义事件"));
3、订阅事件
订阅事件,可以在UI中的OnOpen方法中执行订阅事件方法,并且需要在OnClose中取消订阅
GameEntry.Event.Subscribe(TestEvent.EventId, OnTest);
事件方法
private void OnTest(object sender,GameEventArgs e)
{
TestEvent testEvent = (TestEvent)e;
Log.Info(testEvent.EventName+"+成功触发事件");
}
4、取消订阅
GameEntry.Event.Unsubscribe(TestEvent.EventId, OnTest);