NavMeshPlus icon indicating copy to clipboard operation
NavMeshPlus copied to clipboard

Nav Agent doesn't find the mesh when programatically instantiated

Open drizztdourden08 opened this issue 1 year ago • 2 comments

Hi,

I want to report a potential issue when spawning nav agents on an existing mesh.

As a reference, I did open the following issue (To which I couldn't respond for a long times due to special circumstances, sorry for that): #154

After a lot of troubleshooting and nothing really making any sense, It worked in another scene where I replicated the demo, but then I saw it didn't when I programmatically spawned navAgent on the mesh, returning an error message saying it didn't find a close enough mesh. I did find a workaround by disabling the nav agent component and re-enabling it in the "start" function. it then finds the "closest mesh" and works normally from there.

All these times, I thought my mesh wasn't good and that I wasn't refreshing it properly but It was just fine.

So yeah. I think the nav agent might try to find the mesh before it's actually ready and thus, doesn't find it. I'm not sure exactly.

Just as reference, the code for me enemy that uses the mesh:

        private void Awake() {
            tag = "Enemy";

            nav = GetComponent<NavMeshAgent>();
            nav.updateRotation = false;
            nav.updateUpAxis = false;
            nav.speed = speed;

            if (layers.HasFlag(Layer.Air))
                nav.baseOffset = 5.0f;
        }

        private void Start() {
            nav.enabled = true;
        }

and just in case the way I instantiate it is important, here's the code:

        public static GameObject InstantiateFromPrefab(GameObject prefab, Vector3? position, Quaternion? rotation, Transform parent, string newName) {
            if (prefab == null) return null;

            GameObject instantiatedObject = Object.Instantiate(prefab);
            if (position.HasValue) {
                instantiatedObject.transform.position = position.Value;
            }
            if (rotation.HasValue) instantiatedObject.transform.rotation = rotation.Value;
            if (parent != null) instantiatedObject.transform.SetParent(parent, false);
            if (newName != null) instantiatedObject.name = newName;

            return instantiatedObject;
        }

drizztdourden08 avatar Oct 08 '23 05:10 drizztdourden08

there is a lot of those peculiarities with Unity) But Agent is native unity component, so there is nothing I can do except add some text in wiki

h8man avatar Oct 08 '23 22:10 h8man

I get it.

That'd be great to document for the next person who gets into the same issue. I'm probably not alone generating nav agent through code. :)

thanks

drizztdourden08 avatar Oct 08 '23 23:10 drizztdourden08