I've successfully created a wander script using a NavMeshAgent, but it's moving too fast and I can't figure out how to slow it down. It may just be that I don't fully understand how the NavMeshAgent works yet, but it's driving me nuts since I've tinkered with the speed and acceleration to the low end values of 0.0005 and that resulted in almost no movement. The following video makes it look like the agent isn't moving, but it is (just really slowly).When I select the capsule that I've added the NavMeshAgent to in the inspector it just takes off, which to me is even weirder behavior. With all of the above out of the way, my wander script is pretty straight forward: Code (CSharp): using System.Collections; using UnityEngine; using UnityEngine.AI; [RequireComponent(typeof(NavMeshAgent))] public class Wander : MonoBehaviour { #region Fields private NavMeshAgent _navMeshAgent; #endregion #region Properties [field: SerializeField] public int NavigationSamplerLayer { get; set; } = 0; [field: SerializeField] public float DelayBetweenRoutes { get; set; } = 3; [field: SerializeField] public float MaximumRouteDistance { get; set; } = 10; #endregion void Awake() { if (!TryGetComponent(out _navMeshAgent)) { Debug.LogError($"Wanderer `{name}` unable to locate a NavMeshAgent on wake."); return; } StartCoroutine(UpdateWander()); } IEnumerator UpdateWander() { while (true) { _navMeshAgent.SetDestination(GetNewWaypoint()); while (_navMeshAgent.velocity.magnitude > 0.5f) yield return new WaitForSeconds(1); yield return new WaitForSeconds(DelayBetweenRoutes); } } public Vector3 GetNewWaypoint() { NavMesh.SamplePosition(transform.position + Random.insideUnitSphere * MaximumRouteDistance, out NavMeshHit navHit, MaximumRouteDistance, NavigationSamplerLayer); return navHit.position; } } How can I slow it down?
One problem I found so far is in the fact UpdateWander was continuously setting a new waypoint. Adding a boolean to determine if a new path is needed helps: Code (CSharp): IEnumerator UpdateWander() { while (true) { if (_newPathNeeded) { _navMeshAgent.SetDestination(GetNewWaypoint()); _newPathNeeded = false; } while (_navMeshAgent.velocity.magnitude > 0.5f) yield return new WaitForSeconds(1); _newPathNeeded = true; yield return new WaitForSeconds(DelayBetweenRoutes); } } But it's still having issues. Still debugging and reviewing, will post any new information as I find it.
After some more adjustments, it turns out the issue was contained to the UpdateWander method. After adjusting it, the object will wander to a location, wait a moment, then wander to a new location. Code (CSharp): IEnumerator UpdateWander() { while (true) { if (!_firstRun) yield return new WaitForSeconds(DelayBetweenRoutes); else _firstRun = false; if (!_navMeshAgent.hasPath) { _navMeshAgent.SetDestination(GetNewWaypoint()); yield return new WaitUntil(() => _navMeshAgent.hasPath); } else yield return new WaitUntil(() => !_navMeshAgent.hasPath); } }