UnityRef is currently in early development. Some features may be incomplete and/or not functioning.

UNITYREF

Your Pit Stop For Solving ANYTHING in Unity

architecture

[NavMesh] Fix AI Agent Teleporting to Origin on Start

Solution

animationpathfindinganimatortransformnavmesh

Unity 2021.3.x - Unity 6.3.x

Published 13 days ago

Issue

 The NavMeshAgent unexpectedly snaps to the world origin (0, 0, 0) coordinates the moment Play Mode is entered. This issue occurs even when the agent is manually placed on a valid NavMeshSurface and typically ignores the initial Transform position set in the Editor.

Teleportation is frequently caused by the Animator component initializing root transform data before the NavMeshAgent synchronizes with the NavMesh. Disabling the Animator or using Warp() resolves the conflict.

Explanation

The behavior where an agent snaps to (0,0,0) usually stems from the Animator component initializing before the NavMeshAgent has sampled a valid position on the NavMesh. Even with Apply Root Motion unchecked, the Animator can reset the Transform if it contains an animation that affects the root position or if the rig is not properly synchronized with the navigation system. This is especially common in Unity 6 when using the new NavMeshSurface workflow.

Follow these steps to resolve the positioning conflict:

  1. Select the affected AI agent in the Hierarchy.
  2. Locate the Animator component and temporarily disable it to verify if the teleportation ceases.
  3. Ensure the agent is placed within the bounds of a baked NavMeshSurface. If the agent is too far from a valid surface, it may fail to find a valid coordinate and default to the origin.
  4. If using Apply Root Motion, ensure that the Animator is set to Animate Physics in the Update Mode if the agent relies on rigidbodies, or ensure the NavMeshAgent is updated via script to follow the Animator.

Additional Tips

  • Use NavMeshAgent.Warp() in a Start or Awake method to explicitly force your script to position the agent onto a specific position if the automatic placement fails.
  • Check if the Animator has a default state with an animation that possesses keyframes at (0,0,0) in world space.
  • Verify that the NavMeshSurface is actually baked; a missing or outdated NavMeshData asset can cause agents to lose their reference point.

Copy


using UnityEngine;
using UnityEngine.AI;

[RequireComponent(typeof(NavMeshAgent))]
public class AgentPositionFixer : MonoBehaviour
{
    private void Awake()
    {
        NavMeshAgent agent = GetComponent<NavMeshAgent>();
        
        // Ensure the agent is warped to the intended transform position
        // This overrides any Animator initialization that might pull the agent to (0,0,0)
        if (agent.isOnNavMesh)
        {
            agent.Warp(transform.position);
        }
    }
}

Related Posts Haven't quite found a solution to your problem? We think these posts might help you.

Content inspired by a Unity discussion post.