先在 Events 脚本中,编写一个继承 IEvent 接口的类,作为一个事件
public readonly struct TestEvent : IEvent
{
public readonly string Test;
// 不写变量,可作为空参数事件使用
public TestEvent(string test)
{
Test = test;
}
}
再到需要订阅的脚本中,编写以下主要代码,缺少一行都无法使用
public class TestEventBinding : MonoBehaviour
{
// 事件绑定
private EventBinding<TestEvent> _testEventBinding;
private void Awake()
{
// 初始化并绑定方法
_testEventBinding = new EventBinding<TestEvent>(OnTestEvent);
}
private void Start()
{
// 在事件总线中注册这个事件绑定
EventBus<TestEvent>.Register(_testEventBinding);
}
// 被绑定的方法
private void OnTestEvent(TestEvent args)
{
Debug.Log($"Test: {args.Test}");
}
}
最后,在相关代码中发布事件
public class TestEventRaise : MonoBehaviour
{
private void Start()
{
// 触发事件
EventBus<TestEvent>.Raise(new TestEvent("Event Bus"));
}
}
可以使用以下写法注销事件绑定,避免事件触发时报空
public class TestEventBinding : MonoBehaviour
{
// 事件绑定
private EventBinding<TestEvent> _testEventBinding;
private void Awake()
{
// 初始化并绑定方法
_testEventBinding = new EventBinding<TestEvent>(OnTestEvent);
}
private void OnEnable()
{
// 注册事件绑定
EventBus<TestEvent>.Register(_testEventBinding);
}
private void OnDisable()
{
// 注销事件绑定
EventBus<TestEvent>.Deregister(_testEventBinding);
}
private void OnDestroy()
{
// 注销事件绑定
EventBus<TestEvent>.Deregister(_testEventBinding);
}
// 被绑定的方法
private void OnTestEvent(TestEvent args)
{
Debug.Log($"Test: {args.Test}");
}
}
public class TestEventBinding : MonoBehaviour
{
// 事件绑定
private EventBinding<TestEvent> _testEventBinding;
private void Awake()
{
// 初始化并绑定方法
_testEventBinding = new EventBinding<TestEvent>(OnTestEvent);
_testEventBinding.Add(OnTestEvent2);
}
// 被绑定的方法,有参
private void OnTestEvent(TestEvent args)
{
Debug.Log($"Test: {args.Test}");
}
// 被绑定的方法二,无参
private void OnTestEvent2()
{
Debug.Log("Test: null");
// 这样可移除,类似仅首次触发
_testEventBinding.Remove(OnTestEvent2);
}
}