SetDestination issue

Hello all, I’ve a navmesh agent attached to my enemy. I want my enemy to move close to the player upto a distance - of say 5 units, and then attack it (ranged attack , attack animation is “attack1”)

Here’s my Update() function code…This script is attached to the enemy AI

void Update () {
        
        
        d=Vector3.Distance(target.transform.position, this.transform.position);
        if((d>5)&&(d<10))
        {    //Debug.Log ("distance = " +d);
            animation.Play("move");
            
            agent.SetDestination(target.transform.position); //problem line

        }
        else if (d<5)
        {    transform.LookAt(target.transform.position);
            animation.Play("attack1");
        }
    }

The problem is that the SetDestination() is making the enemy literally “jump” on the target (player). It’s not actually stopping within 5 units of distance, so "agent.SetDestination(target.transform.position); " needs to be tweaked somehow so that the enemy stops within 5 units of my target player…

What this code is doing actually is that the enemy runs into my player unit and then starts playing the attack animation. I want the enemy to play the attack animation from a distance of 5 units from the player.

Within your else conditional while distance is < 5 you could simply place

agent.ResetPath();
agent.Stop();

I’m pretty sure ResetPath will stop movement as well, so you probably don’t need to call the Stop method.

edit: Alternatively you can do some math to offset your destination by 5 units before assigning it to SetDestination, rather then setting the agents destination directly on top of the other unit

Thanks a lot…I didn’t know much about the Reset() method…