I have to add a delay between disabling NavMeshAgent and setting rotation or it wont work?

I have a NavMeshAgent that moves around, and when he sees player he rotates towards player and shoots.

I tried implementing this like so:

agent.enabled = false;
transform.rotation = GetDirection();

But for some reason 20% of the time, the rotation wouldnt get set properly.

So I tried making it a Coroutine:

agent.enabled = false;

yield return new WaitForSeconds(0.1f);

transform.rotation = GetDirection();

Now it works every time, (yield return null did not work), what could be causing this? Rly dont want to use this ugly solution.

Been a while since I touched NavMesh stuff, but looking at the docs I see properties such as isStopped and updateRotation that might be a more direct means of allowing you to aim the agent. Maybe even just have the actual character as a child of the nav mesh agent and have it face in the right direction, being it the direction it’s headed in, or towards a target.

As to why this happens, probably just a race condition. I don’t imagine agents are updated every frame, so potentially even when you disable it, it may still be in control of the transform for a frame or two.

Yes adding the agent to a child game object like @spiney199 suggested would be the straightforward approach, if you don’t want to deal with some (complex?) State just for rotation/movement coordination (IsMoving, IsRotating…)

I think he suggested adding the agent to the parent and having the mesh as a child, and controlling the mesh rotation, no?

ah yes maybe that would make things easier, so basically I rotate the child mesh (what you call character) so it’s visually facing the right dir, right?

When I made a game with agents I never let them have control of rotation. You often want them to look at the player or a collectable item. If there’s nothing around to LookAt then make them look in the direction of travel, or scan/spin around looking for trouble.

That’s a nice idea actually. So u just disable agent rotation in Awake?

Yep! :slight_smile: