Search Unity

Want AI to follow the player, NavMeshAgent

Discussion in 'Navigation' started by doperganger, Apr 18, 2021.

  1. doperganger

    doperganger

    Joined:
    Apr 8, 2020
    Posts:
    1
    Hello everyone,
    I have set up the Navmesh Agents to follow my player as you can see in the attached image, but only those prefabs in scene hierarchy window are able to follow the player. The agents which I have instantiated from the "Spawner" script, they wont follow the player.
    It would mean alot if solved.
    Thankyou!

    Spawner Script:
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class Spawner : MonoBehaviour
    {

    public Wave[] waves;
    public Enemy enemy;
    public Transform spawnPoint;

    Wave currentWave;
    int currentWaveNumber;

    int enemiesRemainingToSpawn;
    float nextSpawnTime;


    private void Start()
    {
    NextWave();
    }
    private void Update()
    {
    if (enemiesRemainingToSpawn > 0 && Time.time > nextSpawnTime)
    {
    enemiesRemainingToSpawn--;
    nextSpawnTime = Time.time + currentWave.timebetweenSpawns;

    Enemy spawnedEnemy = Instantiate(enemy, spawnPoint.position, Quaternion.identity) as Enemy;


    }
    }

    void NextWave()
    {

    currentWaveNumber++;
    currentWave = waves[currentWaveNumber - 1];
    enemiesRemainingToSpawn = currentWave.enemyCount;
    }

    [System.Serializable]
    // Start is called before the first frame update
    public class Wave
    {

    public int enemyCount;
    public float timebetweenSpawns;
    }
    }





    Enemy Script:

    using System.Collections;

    using UnityEngine;
    using UnityEngine.AI;


    public class Enemy : MonoBehaviour
    {

    public Transform player;
    public NavMeshAgent enemy;

    // Start is called before the first frame update
    void Start()
    {
    enemy = GetComponent<NavMeshAgent>();


    }


    // Update is called once per frame
    void Update()
    {
    enemy.SetDestination(player.position);
    }
    }
     

    Attached Files: