I have a moving object that travels at a constant speed without navigation. At some point, I turn on navigation and the moving object is then controlled by the NavMeshAgent.
When I enable the NavMeshAgent, there is a very visible loss in speed, until the NavMeshAgent “catched up” again. I set the NavMeshAgent.speed to the same value that’s used to move the object without NavMeshAgent. And turning off navigation also does not cause such speed difference glitch, so I guess it’s something with the navigation system.
Below you can find my test project. The cube just moves forward and every time I enable the NavMeshAgent, the speed loss occurs. How can I avoid that? I want that there is no visible glitch when turning on navigation.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class MovingObject : MonoBehaviour
{
[SerializeField] NavMeshAgent m_Agent = default;
[SerializeField] Transform m_NavDestination = default;
[SerializeField] float m_Speed;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
if (!m_Agent.enabled)
{
m_Agent.enabled = true;
NavMeshPath path = new NavMeshPath();
NavMesh.CalculatePath(transform.position, m_NavDestination.position, ~0, path);
m_Agent.SetPath(path);
//m_Agent.SetDestination(m_NavDestination.position);
m_Agent.speed = m_Speed;
m_Agent.acceleration = m_Speed;
if (m_Agent.pathPending)
Debug.LogWarning("NavMeshAgent path is pending");
}
else
{
m_Agent.enabled = false;
}
}
if (!m_Agent.enabled)
{
transform.position += Vector3.forward * m_Speed * Time.deltaTime;
}
}
void OnGUI()
{
GUI.matrix = Matrix4x4.Scale(Vector3.one * 2);
GUI.Label(new Rect(10, 10, 500, 500),
$"Press SPACE to toggle\n"
+ $"NavMeshAgent.enabled = {m_Agent.enabled}\n"
//+ $"NavMeshAgent.pathPending = {m_Agent.pathPending}\n"
);
}
}
6756250–779626–NavMeshAgentTest.zip (28.4 KB)