Why is my enemy gets destroyed when i start the game

Why is my enemy gets destroyed when i start the game
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyPathing : MonoBehaviour
{

[SerializeField] List<Transform> waypoints;
[SerializeField] float moveSpeed = 2f;
int waypointIndex = 0;

// Start is called before the first frame update
void Start()
{
    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);
        }

    }
}

}

Because looks like that - (transform.position == targetPosition) never completes and the else function is used.

okay thx mate

I guess you have put this in wrong place.

else
        {
            Destroy(gameObject);
        }

It should be one level higher.

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

            transform.position = Vector2.MoveTowards(transform.position, targetPosition, movementThisFrame);

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

Privacy & Terms