Nav Mesh Agent Set Destination#
Navigation / Nav Mesh Agent / Nav Mesh Agent Set Destination
Description#
Calculates a path to the destination and moves the Nav Mesh Agent along it
Parameters#
| Name | Description |
|---|---|
| Nav Mesh Agent | The Nav Mesh Agent component that moves |
| Destination | The position the Nav Mesh Agent tries to reach |
| Wait to Arrive | Waits until the Nav Mesh Agent reaches the destination, the end of the closest path it found, or can no longer move |
Code#
using System;
using UnityEngine;
using UnityEngine.AI;
using VisualScript.Icons;
namespace VisualScript.Runtime
{
[Title("Nav Mesh Agent Set Destination")]
[Category("Navigation/Nav Mesh Agent/Set Destination")]
[Description("Calculates a path to the destination and moves the Nav Mesh Agent along it")]
[Image(typeof(IconNavmeshAgent), ColorTheme.Type.Red)]
[Keywords("Navigation", "NavMesh", "AI", "Pathfinding", "Agent", "Move", "Go", "Walk")]
[Parameter("Nav Mesh Agent", "The Nav Mesh Agent component that moves")]
[Parameter("Destination", "The position the Nav Mesh Agent tries to reach")]
[Parameter("Wait to Arrive", "Waits until the Nav Mesh Agent reaches the destination, the end of the closest path it found, or can no longer move")]
[Serializable]
public class InstructionNavMeshAgentSetDestination : Instruction
{
[SerializeField] private GetGameObject m_NavMeshAgent = new GetGameObject(
new GenTypeGameObject_NavMeshAgent()
);
[SerializeField] private GetVector3 m_Destination = new GetVector3();
[SerializeField] private bool m_WaitToArrive;
[NonSerialized] private NavMeshAgent m_Agent;
[NonSerialized] private Func<bool> m_CallHasArrived;
protected override string GetTitle(GameObject source)
{
string method = TextUtils.ThemeAsKeyword("Set Destination");
return $"{this.m_NavMeshAgent} {method} ({this.m_Destination})";
}
protected override async Awaitable Run(Args args)
{
NavMeshAgent agent = this.m_NavMeshAgent.Get<NavMeshAgent>(args);
if (agent == null) return;
if (!agent.SetDestination(this.m_Destination.Get(args))) return;
if (!this.m_WaitToArrive) return;
this.m_Agent = agent;
this.m_CallHasArrived ??= this.HasArrived;
await this.Until(this.m_CallHasArrived);
this.m_Agent = null;
}
private bool HasArrived()
{
NavMeshAgent agent = this.m_Agent;
if (agent == null || !agent.isActiveAndEnabled || !agent.isOnNavMesh) return true;
if (agent.pathPending) return false;
if (agent.pathStatus == NavMeshPathStatus.PathInvalid) return true;
return agent.remainingDistance <= agent.stoppingDistance;
}
}
}