This code is nearly 100% identical to the lecture typed out in Unity2D Lecture #96. I have no idea why it does not work; the enemy ship does not move to the waypoint’s coordinates, but rather disappears instantly upon runtime.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//COPYRIGHT LOLOLOLOL
public class EnemyPath : MonoBehaviour
{
//Pro tip to self(ownder): "List<type> (variable name)" is NOT an array!
//Config Parameters
[SerializeField] List<Transform> waypoints;
[SerializeField] float moveSpeed = 2f;
[SerializeField] bool ToggleDebugMode = false;
//Variable
int waypointIndex = 0;
// Start is called before the first frame update
void Start()
{
//Retrieves the 1st waypoint's coordinates, and relocates the enemy ship
//To the 1st waypoint.
transform.position = waypoints[waypointIndex].transform.position;
}
// Update is called once per frame
void Update()
{
//StartCoroutine(MoveCor());
Move();
}
/*****
* MOVE
*
* Enemy ship moves to assigned waypoints' coordinates.
*
* targetPos is assigned to the waypoint's coordinates, relaying where the ship should move to.
* movementThisFrame is assigned to movesSpeed * Time.deltaTime (again, to ensure it moves consistently,)
*
* This ship's position is made equal to Vector2.MoveTowards(Vector2 current, Vector2 target, float)
* -"Vector2 current" should be the object's current position, so ideally it's always "transform.position",
* -"Vector2 target" is where the object is assigned to move to.
* -"float" variable is the object's assigned speed. It'll never go faster than this float variable.
*
* The if & else statements check if the ship is at one of the waypoint's coordinates.
* -If it is, increment waypointIndex, thus telling the ship to move to the next waypoint.
* -Else, destroy itself once all waypoints have been visited.
*
* TODO: Add a function that allows it to operate even without waypoints, and it'll despawn once offscreen to the left.
*****/
//THIS JOKE OF A METHOD DOES NOT EXECUTE PROPERLY AT ALL!
//DO I HAVE TO WRITE SOME TERRIBLE SPAGHETTI CODE TO GET THIS TO WORK?!?
private void Move()
{
//Arrays use ".length", and Lists use ".Count".
if (waypointIndex <= waypoints.Count - 1)
{
var targetPos = waypoints[waypointIndex].transform.position;
var movementThisFrame = moveSpeed * Time.deltaTime;
transform.position = Vector2.MoveTowards
(transform.position, targetPos, movementThisFrame);
if (transform.position == targetPos)
{
waypointIndex++;
}
else
{
Destroy(gameObject);
}
}
}
}
EDIT: Updated code to include the rest.