Beginner: NavMesh issue

Hey all, I’m having trouble getting an enemy patrol function to work. In a nutshell, the enemy will move between two points. If the player hits a particular trigger, the enemy abandons patrolling those two points and pursues player.

Unfortunately, I can’t seem to get my method to work. The enemy just stands still. I can get the enemy to pursue the player when I comment out the method and just put “meshAgent.SetDestination(playerMovement.transform.position);” in the Awake function.

Can any of you identify the issue with my Patrol method? Here are the relevant scripts (they’re a bit of a mess, as I’m mainly experimenting).

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.AI;

public class Enemy : MonoBehaviour
{
    int currentPoint;
    public Transform[] patrolPoint;
    float movementSpeed = 5f;

    PlayerMovement playerMovement;
    public NavMeshAgent meshAgent;

   
    void Awake ()
    {
        transform.position = patrolPoint[0].position;
        currentPoint = 0;
        playerMovement = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerMovement>();
        meshAgent = GetComponent<NavMeshAgent>();
      
    }
   
   
    void Update ()
    {
        Patrol();
    }

    private void Patrol()
    {


        if (playerMovement.enemyTrigger == true)
        {
            meshAgent.SetDestination(playerMovement.transform.position);
        }
        else
        {
            if (transform.position == patrolPoint[currentPoint].position)


            { currentPoint++; }
           

            if (currentPoint >= patrolPoint.Length)
            {
                currentPoint = 0;
            }
            transform.position = Vector3.MoveTowards(transform.position, patrolPoint[currentPoint].position, movementSpeed * Time.deltaTime);

        }
           
       

     
    }

}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {
  
    public float moveSpeed;
    float maxSpeed = 5;
    Rigidbody rb;
    Vector3 input;
    public Vector3 spawnPoint;
    public GameObject deathParticles;
    MeshRenderer meshRenderer;
    Enemy enemy;
  
    public bool isDead = false;
    public bool enemyTrigger = false;


    void Start ()
    {
        rb = GetComponent<Rigidbody>();
        spawnPoint = transform.position;
        meshRenderer = GetComponent<MeshRenderer>();
        enemy = GameObject.FindGameObjectWithTag("Enemy").GetComponent<Enemy>();
    }

  
  
    void FixedUpdate ()
    {
        input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));

      
         if(rb.velocity.magnitude < maxSpeed)
        {
            rb.AddForce(input * moveSpeed, ForceMode.Acceleration);
        }

        FallDeath();

    }
    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Enemy")
        {
            Die();
        }
        if (other.tag == "EnemyTrigger")
        {
            enemyTrigger = true;
          
        }

    }

    private void OnCollisionEnter(Collision collision)
    {
        if(collision.collider.tag == "Trap")
        {
            Die();
        }
    }

  

    public void Die()
    {
        Instantiate(deathParticles, transform.position, Quaternion.identity);
        meshRenderer.enabled = false;
        rb.isKinematic = true;
        isDead = true;
        transform.position = spawnPoint;


        StartCoroutine (Wait());
    


    }

    void FallDeath()
    {
        if (transform.position.y <= 0.9f)
        {
            Die();
        }
    }

    public IEnumerator Wait()
    {
        if (isDead)
        {
            yield return new WaitForSeconds(2);
          
          
            rb.isKinematic = false;
            isDead = false;
            meshRenderer.enabled = true;

        }
    }

}

I tried using a while loop with the enemyTrigger bool, but that caused Unity to freeze. I appreciate any help you can provide.

In your enemy script try putting public Transform _player; and the drag your player gameobject into the slot, then in your Patrol method add… meshAgent.SetDestination(_player.position);

Thanks for the reply. That didn’t work, unfortunately. I have the same issue. Any other ideas?

Is there some sort of conflict between:

“transform.position = Vector3.MoveTowards(transform.position, patrolPoint[currentPoint].position, movementSpeed * Time.deltaTime);”

And using a NavMeshAgent? Since adding a NavMeshAgent component, the above line doesn’t work at all. The associated object sort of vibrates while staying in the same position.

The navmesh will try to move the gameobject its attached too.
So if your move towards and the agent are both trying to move the same object you could see the jitter.

Also try using .destination instead of setdestination. See if that makes a difference.
I think there might be a difference that is not clear in the documentation.

Thanks for the reply. There appears to be a problem with my if statement, though. I can’t for the life of me figure out why.

This line moves the object to the desired point just fine (there are two elements in the array):

    private void Patrol()
    {
      
        transform.position = Vector3.MoveTowards(transform.position, patrolPoint[1].position, movementSpeed * Time.deltaTime);
    }

However, when I use an if statement to move between two points, the object stays still (currentPoint is set to 0 in the awake function):

  private void Patrol()
    {
         if(transform.position == patrolPoint[currentPoint].position)
         {
             currentPoint++;
         }
         if(currentPoint >= patrolPoint.Length)
         {
             currentPoint = 0;
         }


        transform.position = Vector3.MoveTowards(transform.position, patrolPoint[currentPoint].position, movementSpeed * Time.deltaTime);
    }

Any idea why the above if statement won’t work? Again, it worked fine before I added a NavMesh, so I thought that might be the problem. However, the object moves just fine if I remove the if statement.

Let me know if you need more information in order to help. I honestly can’t think of a single reason why that if statement doesn’t work now.

You have two if statements. So not sure which is your problem.

  private void Patrol()
         if(transform.position == patrolPoint[currentPoint].position)

Be careful with this kind of check. It is typically very hard to have this actually be 100% equal. Unless you are guaranteeing it to be somehow. It is better to use some kind of (is close enough to check). Think distance or better a squared distance check.

So if your navmesh agent is still trying to move the character too, you may never exactly arrive at the location using the movetowards.

  private void Patrol()
         if(currentPoint >= patrolPoint.Length)
         {
             currentPoint = 0;
         }

If it is this if statement, I am not sure, unless your currentPoint location is being reset to your objects transform.position. So they are the same place.