At this point I have seen this error more then I want to and learned how to deal with it. Today however it just seems weird to me so I don’t even know how to continue fixing this.
When a Enemy is spawn after starting the game I get a NullReference Error telling me there is something wrong in my PathFinding, knowing after previous tests that my Pathfinding works perfectly without Enemies I thought it had to be something else in the EnemyMover (But I could be wrong). i’ve added a few Debugs there to see where it went wrong and it seems like it manages to move a few frames and then stops. This alone already seems really odd to me (If it was a NullReference I would say it would crash instantly) but it turns out that if i just unpause the game everythings works well and as intended. So it is just at the start somewhere. I have no idea what i’ll have to show here that might help so please let me know if you want to see something.
My enemy mover script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMover : MonoBehaviour
{
[SerializeField] [Range(0,5)]float speed = 1f;
List<Node> path = new List<Node>();
Enemy enemy;
GridManager gridManager;
PathFinder pathfinder;
// Start is called before the first frame update
void OnEnable()
{
FindPath();
ReturnToStart();
StartCoroutine(WalkPath());
}
void Awake()
{
enemy = FindObjectOfType<Enemy>();
gridManager = FindObjectOfType<GridManager>();
pathfinder = FindObjectOfType<PathFinder>();
}
void FindPath()
{
path.Clear();
path = pathfinder.GetNewPath();
Debug.Log("Path found");
}
void ReturnToStart()
{
transform.position = gridManager.GetPositionfromcoordinates(pathfinder.StartCoordinates);
Debug.Log("ReturnToStart");
}
void FinishPath()
{
gameObject.SetActive(false);
enemy.StealGold();
}
IEnumerator WalkPath()
{
Debug.Log("WalkStarted");
for (int i=0; i < path.Count; i++)
{
float travelPercent = 0f;
Vector3 startPosition = transform.position;
Vector3 endPosition = gridManager.GetPositionfromcoordinates(path[i].coordinates);
transform.LookAt(endPosition);
while(travelPercent < 1)
{
Debug.Log("while walking going well");
travelPercent += Time.deltaTime * speed;
transform.position = Vector3.Lerp(startPosition,endPosition,travelPercent);
yield return new WaitForEndOfFrame();
Debug.Log("Frame restart");
}
}
FinishPath();
}
}