Enemy doesn't follow waypoint after instantiate from EnemySpawner.CS

EnemySpawner.cs

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

public class EnemySpawner : MonoBehaviour
{
[SerializeField] List waveConfigs;
int startingWave = 0;

// Start is called before the first frame update
void Start()
{
    var currentWave = waveConfigs[startingWave];
    StartCoroutine(SpawnAllEnemiesInWave(currentWave));
}

private IEnumerator SpawnAllEnemiesInWave(WaveConfig waveConfig)
{
    Instantiate(
        waveConfig.GetEnemyPrefab(),
        waveConfig.GetWaypoints()[0].transform.position,
        Quaternion.identity);
    yield return new WaitForSeconds(waveConfig.GetTimeBetweenSpawns());

}

}

EnemyPathing.cs

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

public class EnemyPathing : MonoBehaviour
{
[SerializeField] WaveConfig waveConfig;
List waypoints;
[SerializeField] float moveSpeed = 2f;
int waypointIndex = 0;

// Start is called before the first frame update
void Start()
{
    waypoints = waveConfig.GetWaypoints();
    transform.position = waypoints[waypointIndex].transform.position;
}

// Update is called once per frame
void Update()
{
    Move();
}

private void Move()
{
    if (waypointIndex <= waypoints.Count - 1)
    {
        var targetPosition = waypoints[waypointIndex].transform.position;
        var movementThisFrame = moveSpeed * Time.deltaTime;
        transform.position = Vector2.MoveTowards(transform.position, targetPosition, movementThisFrame);

        if (transform.position == targetPosition)
        {
            waypointIndex++;
        }
    }
    else
    {
        Destroy(gameObject);
    }
}

}

WaveConfig.cs

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

[CreateAssetMenu(menuName = “Enemy Wave Config”)]
public class WaveConfig : ScriptableObject
{
[SerializeField] GameObject enemyPrefab;
[SerializeField] GameObject pathPrefab;
[SerializeField] float timeBetweenSpawns = 0.05f;
[SerializeField] float spawnRandomFactor = 0.3f;
[SerializeField] int numberOfEnemies = 5;
[SerializeField] float moveSpeed = 2f;

// other methods can pull this information.
public GameObject GetEnemyPrefab() {return enemyPrefab;}

public List<Transform> GetWaypoints()
{
    var waveWaypoints = new List<Transform>();
    foreach (Transform child in pathPrefab.transform)
    {
        waveWaypoints.Add(child);
    }

    return waveWaypoints;
}

public float GetTimeBetweenSpawns() { return timeBetweenSpawns; }

public float GetSpawnRandomFactor() { return spawnRandomFactor; }

public int GetNumberOfEnemies() { return numberOfEnemies; }

public float GetMoveSpeed() { return moveSpeed; }

}

I found the issue. EnemyPathing.CS was not included in my Enemy prefab with a wave inserted in the field.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms