IEnumerator Pathfind() { if (pathfindingScheduled) { yield break; } pathfindingScheduled = true; lastPathfindedPosition = target.position; float waitSeconds = pathfindingRandomMaxWaitTime; bool pathFound = false; if (pathfinding.AreNeighbours(lastPathfindedPosition, target.position) && path != null) { path.AddLast(target.position); pathFound = true; waitSeconds = 0; } yield return(new WaitForSeconds(Random.Range(0, waitSeconds))); lastPathfindedPosition = target.position; if (pathfinding == null) { pathfinding = GameObject.FindGameObjectWithTag("Map").GetComponent <MapGenerator>().pathfinding; } if (!pathFound) { foreach (var enemy in enemiesNearby) { if (enemy.lastPathfindedPosition == lastPathfindedPosition && enemy.path != null) { path = new LinkedList <Vector3>(); foreach (var pos in enemy.path) { path.AddLast(pos); } pathFound = true; break; } } } if (!pathFound) { path = pathfinding.GetPath(transform.position, lastPathfindedPosition); } if (path != null && path.Count > 1) { CurrentState = State.Moving; path.RemoveLast(); path.AddLast(lastPathfindedPosition); nextStep = path.First.Value; path.RemoveFirst(); } else { CurrentState = State.Idle; } pathfindingScheduled = false; }