OldBlueWater/BlueWater/Assets/02.Scripts/Npc/NpcStateMachine.cs

85 lines
2.5 KiB
C#

using System.Collections;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.AI;
// ReSharper disable once CheckNamespace
namespace BlueWaterProject
{
public class NpcStateMachine : MonoBehaviour
{
private NavMeshAgent agent;
public INpcState CurrentState { get; private set; }
public NpcStateContext Context { get; private set; } = new NpcStateContext();
private Coroutine coroutine;
public void ChangeState(INpcState newState)
{
ConePreviousState();
StopCoroutines();
CurrentState?.OnExit(this);
CurrentState = newState;
CurrentState.OnEnter(this);
}
public void Update()
{
CurrentState?.OnUpdate(this);
}
public void RestorePreviousState()
{
if (Context.PreviousState != null)
{
ChangeState(Context.PreviousState.Clone());
if (Context.PreviousDestination.HasValue)
{
agent.destination = Context.PreviousDestination.Value; // 이전 목적지로 설정
}
else
{
// 목적지가 없는 경우, 다른 처리를 수행하거나 그대로 둡니다.
}
}
else
{
// 이전 상태가 없거나 복제할 수 없는 경우, 기본 상태로 돌아가거나 다른 처리
Debug.LogWarning("No previous state to restore.");
}
}
public void StartWaitCoroutine(float waitTime, UsuallyPointState state)
{
coroutine = StartCoroutine(WaitCoroutine(waitTime, state));
}
private IEnumerator WaitCoroutine(float waitTime, UsuallyPointState state)
{
yield return new WaitForSeconds(waitTime);
state.EndWait();
}
private void StopCoroutines()
{
if (coroutine != null)
{
StopCoroutine(coroutine);
coroutine = null;
}
}
private void ConePreviousState()
{
if (CurrentState != null)
{
var clonedState = CurrentState.Clone();
if (clonedState != null)
{
Context.PreviousState = clonedState;
Context.PreviousDestination = agent.destination;
}
}
}
}
}