Fluid
Fluid

Reputation: 11

How to stop Unity NavMesh Agent for 2 seconds, then resume walking at normal speed

I want the NavMesh agent in Unity to stop walking once my Attack() method is called. Then, after a couple of seconds, I want the AI to start walking again at its normal walking speed.

My code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class AiLoco3 : MonoBehaviour
{
    private Transform player;
    private NavMeshAgent agent;
    Animator animator;


    public float agentSpeed = 2f;

    void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player").transform;
        agent = GetComponent<NavMeshAgent>();
        animator = GetComponent<Animator>();
        
        agent.speed = agentSpeed;


    }

    void Update()
    {
        agent.destination = player.position;
        animator.SetFloat("Speed", agent.velocity.magnitude);

        //Debug.Log(agent.velocity.magnitude);

    }

    public void Attack()
    {
        Debug.Log("ATTACK");
        agent.speed = 0f;

        StartCoroutine(ResumeWalking());
    }

    IEnumerator ResumeWalking()
    {
        yield return new WaitForSeconds(2);

        agent.speed = 2f;
    }

    public void Charge()
    {
        Debug.Log("Run");
        agent.speed = 8f;
        Invoke("ChargeTime", 2.0f);
    }
    public void ChargeTime()
    {
        agent.speed = agentSpeed;

    }

}

The Attack Method is called from another script, and that works perfectly because when the Attack Method is called, it does debug "ATTACK". However, it does not stop walking at all, it just keeps walking. I don't get any error messages.

Upvotes: 1

Views: 279

Answers (1)

A-Fairooz
A-Fairooz

Reputation: 456

Instead of setting the speed to 0, you can use the isStopped property on the agent like so:

    public void Attack()
    {
        Debug.Log("ATTACK");
        agent.isStopped = true;

        StartCoroutine(ResumeWalking());
    }

    IEnumerator ResumeWalking()
    {
        yield return new WaitForSeconds(2);

        agent.isStopped = false;
    }

Upvotes: 0

Related Questions