I’m new to Unity and scripting, but I’ve just come across something strange. I was following a tutorial where we made the enemy move around set points in the play area. It works perfectly in the script that I did while following the tutorial a few days ago. Now that I try to use it for another project, it’s not showing the same behaviors. Here’s the original code:
using UnityEngine;
public class EnemyPatrol : MonoBehaviour
{
public Transform[] patrolPoints;
public float moveSpeed;
private int currentPoint;
private void Start()
{
transform.position = patrolPoints[0].position;
currentPoint = 0;
}
private void FixedUpdate()
{
if(transform.position == patrolPoints[currentPoint].position)
{
currentPoint++;
}
if(currentPoint >= patrolPoints.Length)
{
currentPoint = 0;
}
transform.position = Vector3.MoveTowards(transform.position, patrolPoints[currentPoint].position, moveSpeed * Time.deltaTime);
}
}
If you can’t tell (I’m not sure if it’s written well or poorly), the goal was to make the enemy move around certain points but to be able to add more points if necessary instead of having a set number of points. Again, it worked perfectly in the script that I used with the tutorial. Now that I’ve created a new Unity project with the same parameters set in Unity as the previous project, it doesn’t work. The enemy character starts at patrolPoints[0].position, moves to patrolPoints[1].position, and just stays there. I literally copied and pasted after some frustration just to get it to work the way I wanted it to, but the same thing happened.
Then, I decided to make it as obvious as possible and re-wrote it to just move back and forth between the 2 points that I set in Unity:
using UnityEngine;
public class ColliderBehavior : MonoBehaviour
{
public Transform[] patrolPoints;
public float moveSpeed;
private void Start()
{
transform.position = patrolPoints[0].position;
currentPoint = 0;
}
private void FixedUpdate()
{
if(transform.position == patrolPoints[0].position)
{
transform.position = Vector3.MoveTowards(transform.position, patrolPoints[1].position, moveSpeed * Time.deltaTime);
}
if(transform.position == patrolPoints[1].position)
{
transform.position = Vector3.MoveTowards(transform.position, patrolPoints[0].position, moveSpeed * Time.deltaTime);
}
}
}
With this, it just stays in the position where it starts. What. Is. Happening?