I’m not sure what’s wrong but I keep getting the following error:
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.ThrowHelper.ThrowArgumentOutOfRangeException (System.ExceptionArgument argument, System.ExceptionResource resource) (at :0)
System.ThrowHelper.ThrowArgumentOutOfRangeException () (at :0)
System.Collections.Generic.List`1[T].get_Item (System.Int32 index) (at :0)
EnemyPathing.Start () (at Assets/Scripts/EnemyPathing.cs:17)
This is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class EnemyPathing : MonoBehaviour
{[SerializeField] WaveConfig waveConfig; List<Transform> waypoints; [SerializeField] float moveSpeed = 2f; int waypointIndex = 0; // Start is called before the first frame update void Start() { waypoints = waveConfig.GetWaypoints(); 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 (new Vector2(transform.position.x, transform.position.y), new Vector2(targetPosition.x, targetPosition.y), movementThisFrame); if (transform.position == targetPosition) { waypointIndex++; } } else { Destroy(gameObject); } } }
}
I’m not sure what the problem is. Here’s the code for my WaveConfig script too if it will help
using System.Collections;
using System.Collections.Generic;
using UnityEngine;[CreateAssetMenu(menuName = “Enemy Wave Config”)]
public class WaveConfig : ScriptableObject
{
[SerializeField] GameObject enemyPrefab;
[SerializeField] GameObject pathPrefab;
[SerializeField] float timeBetweenSpawns = 0.5f;
[SerializeField] float spawnRandomFactor = 0.3f;
[SerializeField] int numberOfEnemies = 5;
[SerializeField] float moveSpeed = 2f;public GameObject GetEnemyPrefab() {return enemyPrefab;} public List<Transform> GetWaypoints() { var waveWaypoints = new List<Transform>(); foreach (Transform child in pathPrefab.transform) { waveWaypoints.Add(child); } return waveWaypoints; } public float GetTimeBetweenSpawns() {return timeBetweenSpawns;} public float GetSpawnRandomFactor() {return spawnRandomFactor;} public int GetNumberOfEnemies() {return numberOfEnemies;} public float GetMoveSpeed() {return moveSpeed;}
}
My game will run but it instantly destroys the enemy gameObject instead of having it follow the waypoints