OldBlueWater/BlueWater/Assets/02.Scripts/Npc/NpcStateMachine.cs
2024-01-18 18:01:04 +09:00

95 lines
2.8 KiB
C#

using System.Collections;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.AI;
// ReSharper disable once CheckNamespace
namespace BlueWaterProject
{
public class NpcStateMachine : MonoBehaviour
{
public NavMeshAgent Agent { get; set; }
public INpcState CurrentState { get; private set; }
public NpcStateContext Context { get; private set; } = new NpcStateContext();
private Coroutine coroutine;
public void ChangeState(INpcState newState)
{
ClonePreviousState();
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 ClonePreviousState()
{
if (CurrentState != null)
{
var clonedState = CurrentState.Clone();
if (clonedState != null)
{
Context.PreviousState = clonedState;
Context.PreviousDestination = Agent?.destination;
}
}
}
public void InstantiateObject(GameObject prefab, Vector3 position)
{
Instantiate(prefab, position, Quaternion.identity);
}
public void InstantiateUi(GameObject prefab, Transform parent)
{
Instantiate(prefab, parent);
}
}
}