Enemies destroyed on play

Hello I am having a problem with the enemies being destroyed when the game is run. I followed what the instructor did and I don’t think I made any mistakes, at least none I can find.

Here is the code I am using.

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

public class Pathfinder : MonoBehaviour
{
[SerializeField] WaveConfigSO waveConfig;

List<Transform> waypoints;

int waypointIndex = 0;

void Start()
{
    waypoints = waveConfig.GetWaypoint();
    transform.position = waypoints[waypointIndex].position;
}

void Update()
{
    FollowPath();
}

void FollowPath()
{
    if (waypointIndex < waypoints.Count)
    {
        Vector3 targetPosition = waypoints[waypointIndex].position;
        float delta = waveConfig.GetMoveSpeed() * Time.deltaTime;
        transform.position = Vector2.MoveTowards(transform.position, targetPosition, delta);
        if (transform.position == targetPosition)
        {
            waypointIndex++;
        }
        else
        {
            Destroy(gameObject);
        }
    }
}

}

If I comment out.

        else
        {
            Destroy(gameObject);
        }

The enemies go through their way point movements but of course aren’t destroyed at the end of the sequence.

Thanks.

Your enemy starts at the first waypoint. The Update destroys the enemy when it’s at a waypoint - which it is.

Your problem is in FollowPath(). The else should be for the first if, not the second

// THIS
void FollowPath()
{
    if (waypointIndex < waypoints.Count)
    {
        Vector3 targetPosition = waypoints[waypointIndex].position;
        float delta = waveConfig.GetMoveSpeed() * Time.deltaTime;
        transform.position = Vector2.MoveTowards(transform.position, targetPosition, delta);
        if (transform.position == targetPosition)
        {
            waypointIndex++;
        }
    }
    else
    {
        Destroy(gameObject);
    }
}

// NOT THIS
void FollowPath()
{
    if (waypointIndex < waypoints.Count)
    {
        Vector3 targetPosition = waypoints[waypointIndex].position;
        float delta = waveConfig.GetMoveSpeed() * Time.deltaTime;
        transform.position = Vector2.MoveTowards(transform.position, targetPosition, delta);
        if (transform.position == targetPosition)
        {
            waypointIndex++;
        }
        else
        {
            Destroy(gameObject);
        }
    }
}

That solved my issue.

You must have the eyes of an eagle. I would have never spotted that.

Thank you very much.

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

Privacy & Terms