using System;
using System.Diagnostics;
namespace TEngine
{
///
/// 实体组件基类。
///
public abstract class EntityComponent : IMemory
{
private EntityLogic _owner;
public virtual int Priority => 0;
public virtual bool NeedUpdate => false;
///
/// 组件持有者。
///
public EntityLogic Owner => _owner;
protected internal void OnAwake(EntityLogic owner)
{
_owner = owner;
OnAttach(_owner);
AddDebug();
}
public void Clear()
{
OnDetach(_owner);
ClearAllListener();
RmvDebug();
_owner = null;
}
///
/// 附加到实体上。
/// After Awake()
///
/// 实体逻辑类。
protected virtual void OnAttach(EntityLogic entityLogic)
{
}
///
/// 从实体上移除。
/// Before OnDestroy()
///
/// 实体逻辑类。
protected virtual void OnDetach(EntityLogic entityLogic)
{
}
///
/// 实体组件轮询。
///
/// 逻辑流逝时间,以秒为单位。
/// 真实流逝时间,以秒为单位。
protected internal virtual void OnUpdate(float elapseSeconds, float realElapseSeconds)
{
}
#region 事件相关。
///
/// 增加事件监听。
///
/// 事件Id。
/// 事件回调。
public void AddEventListener(int eventId, Action eventCallback)
{
_owner.Event.AddEventListener(eventId, eventCallback, this);
}
///
/// 增加事件监听。
///
/// 事件Id。
/// 事件回调。
/// 事件参数类型1。
public void AddEventListener(int eventId, Action eventCallback)
{
_owner.Event.AddEventListener(eventId, eventCallback, this);
}
///
/// 增加事件监听。
///
/// 事件Id。
/// 事件回调。
/// 事件参数类型1。
/// 事件参数类型2。
public void AddEventListener(int eventId, Action eventCallback)
{
_owner.Event.AddEventListener(eventId, eventCallback, this);
}
///
/// 增加事件监听。
///
/// 事件Id。
/// 事件回调。
/// 事件参数类型1。
/// 事件参数类型2。
/// 事件参数类型3。
public void AddEventListener(int eventId, Action eventCallback)
{
_owner.Event.AddEventListener(eventId, eventCallback, this);
}
///
/// 增加事件监听。
///
/// 事件Id。
/// 事件回调。
/// 事件参数类型1。
/// 事件参数类型2。
/// 事件参数类型3。
/// 事件参数类型4。
public void AddEventListener(int eventId, Action eventCallback)
{
_owner.Event.AddEventListener(eventId, eventCallback, this);
}
///
/// 清除本组件所有事件监听。
///
public void ClearAllListener()
{
if (_owner != null && _owner.Event != null)
{
_owner.Event.RemoveAllListenerByOwner(this);
}
}
#endregion
#region 编辑器Debug相关
[Conditional("UNITY_EDITOR")]
protected void AddDebug()
{
#if UNITY_EDITOR
if (_owner == null)
{
return;
}
var debugData = _owner.gameObject.GetComponent();
if (debugData == null)
{
debugData = _owner.gameObject.AddComponent();
}
debugData.AddDebugCmpt(GetType().Name);
#endif
}
[Conditional("UNITY_EDITOR")]
protected void RmvDebug()
{
#if UNITY_EDITOR
if (_owner == null)
{
return;
}
var debugData = _owner.gameObject.GetComponent();
if (debugData == null)
{
debugData = _owner.gameObject.AddComponent();
}
debugData.RmvDebugCmpt(GetType().Name);
#endif
}
[Conditional("UNITY_EDITOR")]
public void SetDebugInfo(string key, string val)
{
#if UNITY_EDITOR
if (_owner == null)
{
return;
}
var debugData = _owner.gameObject.GetComponent();
if (debugData == null)
{
debugData = _owner.gameObject.AddComponent();
}
debugData.SetDebugInfo(GetType().Name, key, val);
#endif
}
#endregion
}
}