using UnityEngine;
using UnityEngine.AI;
namespace BlueWaterProject
{
public class FindTableState : INpcState
{
private NavMeshAgent agent;
private TycoonMapInfo tycoonMapInfo;
private Table[] tables;
private bool doSeat;
// Currently assigned seat
private Seat assignedSeat;
public FindTableState(NavMeshAgent agent, TycoonMapInfo tycoonMapInfo)
{
this.agent = agent;
this.tycoonMapInfo = tycoonMapInfo;
tables = tycoonMapInfo.Tables.GetComponentsInChildren
();
}
public void OnEnter(NpcStateMachine npcStateMachine)
{
CheckAndAssignSeat();
}
public void OnUpdate(NpcStateMachine npcStateMachine)
{
var currentTables = tycoonMapInfo.Tables.GetComponentsInChildren();
if (currentTables.Length == tables.Length) return;
tables = currentTables;
CheckAndAssignSeat();
}
private void CheckAndAssignSeat()
{
if (!doSeat)
{
foreach(var table in tables)
{
foreach(var seat in table.SeatPoints)
{
if (seat.IsUsing) continue;
agent.SetDestination(seat.transform.position);
//Relinquish the previously assigned seat
if (assignedSeat != null)
{
assignedSeat.IsUsing = false;
assignedSeat.IsDirty = true;
}
//Assign the new seat
assignedSeat = seat;
assignedSeat.IsUsing = true;
doSeat = true;
return;
}
}
}
Debug.Log("All tables are occupied. No place to sit");
}
public void OnExit(NpcStateMachine npcStateMachine)
{
if (assignedSeat == null) return;
assignedSeat.IsUsing = false;
assignedSeat.IsDirty = true;
}
}
}