Files
test/Assets/PerfectWorld/Scripts/NPC/NPCVisual.cs
T
2025-10-17 17:52:36 +07:00

108 lines
3.2 KiB
C#

using Animancer;
using BrewMonster;
using System;
using System.Collections.Generic;
using UnityEngine;
using static CECModel;
public class NPCVisual : MonoBehaviour
{
[SerializeField] NamedAnimancerComponent namedAnimancer;
protected CECNPC.INFO m_NPCInfo;
[SerializeField] private Queue<string> _animationQueue = new Queue<string>();
[SerializeField] private AnimancerState _currentState;
public CECNPC.INFO GetNPCINFO => m_NPCInfo;
#if UNITY_EDITOR
[SerializeField] bool isDebug;
public void DEBUG(string text)
{
if (!isDebug) return;
BMLogger.LogError(text);
}
#endif
public bool TryPlayAction(string animationName, CECAttackEvent cECAttackEvent, bool isHit = false)
{
#if UNITY_EDITOR
DEBUG("HoangDev: TryPlayAction: " + animationName);
#endif
if (namedAnimancer == null) return false;
if (namedAnimancer.IsPlaying(animationName)) return false;
_currentState = namedAnimancer.TryPlay(animationName);
if (isHit)
{
_currentState.Events.OnEnd = ()=>SetHitOnEnd(cECAttackEvent);
}
return _currentState == null;
}
private void SetHitOnEnd(CECAttackEvent cECAttackEvent)
{
cECAttackEvent.m_bSignaled = true;
}
public void InitNPCEventDoneHandler(CECNPC.INFO iNFO)
{
m_NPCInfo = iNFO;
namedAnimancer = GetComponentInChildren<NamedAnimancerComponent>();
if (namedAnimancer == null)
{
BrewMonster.BMLogger.LogError("animancer == null");
return;
}
EventBus.SubscribeChannel<QueueNPCActionEvent>(m_NPCInfo.nid, OnQueueAction);
EventBus.SubscribeChannel<ClearComActFlagEvent>(m_NPCInfo.nid, OnClearComActFlagEvent);
}
private void OnClearComActFlagEvent(ClearComActFlagEvent @event)
{
_animationQueue.Clear();
}
private void Update()
{
PlayNext();
}
private void OnQueueAction(QueueNPCActionEvent @event)
{
if (!EnqueueAnimation(@event))
{
BMLogger.LogError("HoangDev : EnqueueAnimation Failed");
}
}
public bool EnqueueAnimation(QueueNPCActionEvent @event)
{
if (namedAnimancer == null) return false;
_animationQueue.Enqueue(@event.AnimationName);
return true;
}
private void PlayNext()
{
if (_animationQueue.Count == 0)
{
return;
}
if (_currentState == null) return;
if (_currentState.NormalizedTime < 1f) return;
string animName = _animationQueue.Dequeue();
_currentState = namedAnimancer.TryPlay(animName);
}
private void OnDestroy()
{
EventBus.UnsubscribeAllInChannel(m_NPCInfo.nid);
}
public bool IsAnimationExist(string animationName)
{
if (namedAnimancer == null) return false;
return namedAnimancer.States.TryGet(animationName, out var existingState) ? true : false;
}
public bool IsPlayAnimation()
{
if (namedAnimancer == null) return false;
return namedAnimancer.IsPlaying();
}
public bool IsPlayAnimation(string animationName)
{
if (namedAnimancer == null) return false;
return namedAnimancer.IsPlaying(animationName);
}
}