- Home /
Trying to Stop a NavMeshAgent before it reaches its destination based on a value?
Hi all,
I'm attempting to stop a NavMeshAgent before it reaches its destination based on a maximum move number.
E.g. this would move the agent for a value of 5 and then stop it, whether the destination was reached or not
Now I've been trying to think of a clever way to do this and can't really figure it out.
Ideally I'll be able to subtract 1 each tick of a specific amount of time, E.g. -1 every 0.25 seconds. And when the max number reaches 0 ill do agent.isStopped = true;
if anyone has any ideas about this I would appreciate it.
Thanks
Answer by W01Fi3 · Oct 10, 2018 at 07:09 AM
Do you want this to be based on time, or by distance?
if you want the NavMeshAgent to stop after a specified set of time, I would say make a timer of sorts that will stop the agent after maximum units elapsed.
 using System;
 using System.Collections;
 using UnityEngine;
 using UnityEngine.AI;
 
 public class GoPlaces : MonoBehaviour
 {
     public float MaxTime;
     public float ElapsedTime;
 
     NavMeshAgent Agent;
 
     void Start()
     {
         Agent = GetComponent<NavMeshAgent>();
     }
     public void GoSomewhere()
     {
         Agent.SetDestination(new Vector3(0, 69, 420));
         Agent.isStopped = false;
         StartCoroutine(ItsLateAndICantThinkOfABetterWay());
     }
     IEnumerator ItsLateAndICantThinkOfABetterWay()
     {
         if (ElapsedTime >= MaxTime)
         {
             Agent.isStopped = true;
             StopCoroutine(ItsLateAndICantThinkOfABetterWay());
         }
         yield return new WaitForSeconds(1);
         ElapsedTime++;
     }
 }
 
If you want to stop the agent after a maximum distance, you could try something basic like this
 using System;
 using System.Collections;
 using UnityEngine;
 using UnityEngine.AI;
 
 public class GoPlaces : MonoBehaviour
 {
     public float MaxDistance;
 
     NavMeshAgent Agent;
 
     Vector3 StartingPosition = Vector3.zero;
 
     void Start()
     {
         Agent = GetComponent<NavMeshAgent>();
     }
     void Update()
     {
         if (!Agent.isStopped)
         {
             if (Vector3.Distance(StartingPosition, transform.position) >= MaxDistance)
             {
                 Debug.Log("AGENT, STOP IT NOW");
                 Agent.isStopped = true;
                 StartingPosition = Vector3.zero;
             }
         }
     }
     public void GoSomewhere()
     {
         Agent.SetDestination(new Vector3(0, 69, 420));
         StartingPosition = transform.position;
 
         Agent.isStopped = false;
     }
 }
Just a couple examples, and if you couldn't tell I'm tired >ᴥ<
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                