So I want my Enemy to move to an Waypoint then increase a List so it can move to the next Waypoint, but somehow my Enemy moves to the first Waypoint and then its stuck at this position. A awnser would be a dream! Here's my Code
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
void Start()
{
transform.position = waypoints[waypointIndex].transform.position;
}
// Update
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);
}
}
}
Btw. in the Console Unity says: Assets\Scripts\EnemyPathing.cs(7,38):warning CS0649: Field 'EnemyPathing.waypoints' is never assigned to and will always have its default value null
Ahh, automatic type conversion, my old nemesis.
Here's some code to think about:
var v2 = new Vector2(21, 22);
var v3 = new Vector3(31, 32, 33);
v3 = v2;
print(v3.z);
The above code does not print out 33 like you might expect. It prints out 0. The reason for this is that the third line is actually two operations: An implicit type conversion from Vector2 to Vector3, and then an assignment. When you convert from a smaller vector to a larger one, the extra components get default values of 0.
So when you go and do this:
transform.position = Vector2.MoveTowards
(transform.position, targetPosition, movementThisFrame);
.. you're actually quietly setting transform.position.z to 0. Which would be generally fine, except:
if (transform.position == targetPosition)
.. if targetPosition.z isn't 0, this will never be true, and you'll never move past the first waypoint.
Here is the simplest solution that makes your code do what you want it to:
if ((Vector2)transform.position == (Vector2)targetPosition)
That'll make sure it's only the x and y that will get compared.
However, be aware that your transform.position.z is still getting set to 0, so you might want to do something about that. Here's a very dirty solution:
var temp = transform.position.z;
transform.position = Vector2.MoveTowards
(transform.position, targetPosition, movementThisFrame);
transform.position.z = temp;