playMaker

Author Topic: navmesh agent arrived at destination action  (Read 1927 times)

Twood

  • Junior Playmaker
  • **
  • Posts: 76
navmesh agent arrived at destination action
« on: January 30, 2022, 07:54:42 PM »
Hi. I suspect because Unity is super weird with their navmesh stuff it seems like nobody ever made a proper way to notify you in one action in PM to when your agent finished their path.

That's probably because the answer is weird, you do it like this in c# checking two bools for false:
Code: [Select]
using UnityEngine;


namespace HutongGames.PlayMaker.Actions
{
    [ActionCategory(ActionCategory.NavMeshAgent)]
    [Tooltip("Sends an event when an agent has completed their path (once AI bools hasPath and pathPending are false.) \n" +
        "NOTE: The Game Object must have a NavMeshAgentcomponent attached.")]

    public class AgentArrivedAtDestination : FsmStateAction
    {
        [RequiredField]
        [Tooltip("The Game Object with the Nav Mesh Agent.")]

        public UnityEngine.AI.NavMeshAgent agent;
        private bool checkHasPath;
        private bool checkPathPending;


        [Tooltip("Next event when agent is done with their path.")]
        public FsmEvent agentArrivedEvent;

        [Tooltip("Repeat every frame. For normal purposes this should be ON.")]
        public bool everyFrame;

        public override void OnEnter()

        {
            checkPathPending = agent.pathPending;
            checkHasPath = agent.hasPath;

            if (everyFrame)
            {
                return;
            }

            else if (!checkHasPath && !checkPathPending)
            {
                Fsm.Event(agentArrivedEvent);
            }

            else
            {
                Finish();
            }
        }

        public override void OnUpdate()
        {

            checkPathPending = agent.pathPending;
            checkHasPath = agent.hasPath;

           
                if (!checkHasPath && !checkPathPending)
                {
                    Fsm.Event(agentArrivedEvent);
                    Finish();
                }

        }

        public override void Reset()
        {
            agent = null;
            agentArrivedEvent = null;
            everyFrame = false;
        }


    }
}

Works fine for me using it, but let me know if there's any issue I haven't seen.

edit: cleaned up something that was redundant in code

« Last Edit: February 05, 2022, 03:01:19 PM by Twood »

EpicMcDude

  • Playmaker Newbie
  • *
  • Posts: 45
Re: navmesh agent arrived at destination action
« Reply #1 on: February 01, 2022, 12:15:42 PM »
Awesome, thanks for the action. I'll be trying this out later today, if this works out it can eliminate having to use 3 actions just to check if the agent has arrived!