【发布时间】:2020-04-03 06:05:32
【问题描述】:
我想将 ScriptableObject 与 UnityEvent 和 GenericObject 用法结合起来。我的最终目标是创建通用事件和侦听器,然后使用 ScriptableObject 创建特定事件,例如GameObject、int 等,并与各自的侦听器一起处理这些。
这是我到目前为止的代码:
EventTemplate.cs
using System.Collections.Generic;
using UnityEngine;
public class EventTemplate<T> : ScriptableObject {
private List<ListenerTemplate<T>> listeners = new List<ListenerTemplate<T>>();
public void Raise(T go) {
for (int i = listeners.Count - 1; i >= 0; i--) {
listeners[i].OnEventRaised(go);
}
}
public void RegisterListener(ListenerTemplate<T> listener) {
listeners.Add(listener);
}
public void UnregisterListener(ListenerTemplate<T> listener) {
listeners.Remove(listener);
}
}
ListenerTemplate.cs
using UnityEngine;
using UnityEngine.Events;
[System.Serializable]
public class ResponseEvent<T> : UnityEvent<T> { }
public class ListenerTemplate<T> : MonoBehaviour {
//[SerializeField]
public EventTemplate<T> gameEvent;
//[SerializeField]
public ResponseEvent<T> response;
private void OnEnable() {
gameEvent.RegisterListener(this);
}
private void OnDisable() {
gameEvent.UnregisterListener(this);
}
public void OnEventRaised(T go) {
response.Invoke(go);
}
}
现在,当我拥有两种泛型类型时,我为int 类型创建了一个事件和一个侦听器。
这是两个文件:
EventInt.cs
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New Event Template", menuName = "Stage Management/Event Templates/Event Int")]
public class EventInt : EventTemplate<int> {
}
和ListenerInt.cs
using UnityEngine;
using UnityEngine.Events;
[System.Serializable]
public class ResponseInt : ResponseEvent<int> { }
public class ListenerInt : ListenerTemplate<int> {
}
然后我的期望是,一旦我通过编辑器将ListenerInt.cs 添加到特定游戏组件,我将能够访问gameEvent 和response,就像我为int 类型定义UnityEvent 一样访问它们。
然而,现实情况是我无法通过编辑器看到/访问gameEvent 和response。
【问题讨论】: