Unity Code C#
using UnityEngine;
using UnityEngine.AI;
using TMPro;
public class NavigateByPersonId : MonoBehaviour
{
public TMP_Text personId;
public Transform targetLocation0;
public Transform targetLocation1;
public Transform targetLocation2;
public MonoBehaviour thirdPersonController;
private NavMeshAgent agent;
private CharacterController controller;
private string lastId = "";
private bool isNavigating = false;
void Awake()
{
agent = GetComponent<NavMeshAgent>();
controller = GetComponent<CharacterController>();
DisableNavMeshControl();
}
void Update()
{
CheckInputId();
CheckArrival();
}
void CheckInputId()
{
if (personId == null) return;
string currentId = personId.text.Trim();
if (currentId != lastId && !string.IsNullOrEmpty(currentId))
{
lastId = currentId;
switch (currentId)
{
case "1":
GoTo(targetLocation0);
break;
case "2":
GoTo(targetLocation1);
break;
case "3":
GoTo(targetLocation2);
break;
}
}
}
void GoTo(Transform target)
{
if (target == null) return;
EnableNavMeshControl();
agent.SetDestination(target.position);
}
void CheckArrival()
{
if (!isNavigating || !agent.enabled) return;
if (!agent.pathPending && agent.remainingDistance <= agent.stoppingDistance)
{
if (!agent.hasPath || agent.velocity.sqrMagnitude < 0.01f)
{
DisableNavMeshControl();
}
}
}
void EnableNavMeshControl()
{
if (thirdPersonController != null) thirdPersonController.enabled = false;
if (controller != null) controller.enabled = false;
agent.enabled = true;
agent.Warp(transform.position);
isNavigating = true;
}
void DisableNavMeshControl()
{
if (agent.enabled)
{
agent.ResetPath();
agent.enabled = false;
}
if (controller != null) controller.enabled = true;
if (thirdPersonController != null) thirdPersonController.enabled = true;
isNavigating = false;
}
}