public DynamicWaypoint NextWaypoint(DynamicWaypoint previousWaypoint) { if (_connections.Count == 0) { //No waypoints? Retrun null and complain. Debug.LogError("Insufficient waypoint count."); return(null); } else if (_connections.Count == 1 && _connections.Contains(previousWaypoint)) { //Only one waypoint and its the previous one? Just use that. return(previousWaypoint); } else //Otherwise, find a random one that isn't the precious one. { DynamicWaypoint nextWaypoint; int nextIndex = 0; do { nextIndex = UnityEngine.Random.Range(0, _connections.Count); nextWaypoint = _connections[nextIndex]; } while (nextWaypoint == previousWaypoint); return(nextWaypoint); } }
private void SetDestination() { if (_waypointsVisited > 0) { DynamicWaypoint nextWaypoint = _currentWaypoint.NextWaypoint(_previousWaypoint); _previousWaypoint = _currentWaypoint; _currentWaypoint = nextWaypoint; } Vector3 targetVector = _currentWaypoint.transform.position; _navMeshAgent.SetDestination(targetVector); _travelling = true; }
// Use this for initialization void Start() { _navMeshAgent = this.GetComponent <NavMeshAgent>(); if (_navMeshAgent == null) { Debug.LogError("The nav mesh agent component is not attached to " + gameObject.name); } else { if (_currentWaypoint == null) { //Set it at random. //Grab all waypoint objects in scene. GameObject[] allWaypoints = GameObject.FindGameObjectsWithTag("Waypoint"); if (allWaypoints.Length > 0) { while (_currentWaypoint == null) { int random = UnityEngine.Random.Range(0, allWaypoints.Length); DynamicWaypoint startingWaypoint = allWaypoints[random].GetComponent <DynamicWaypoint>(); //i.e. we found a waypoint. if (startingWaypoint != null) { _currentWaypoint = startingWaypoint; } } } else { Debug.Log("Failed to find any waypoints for use in the scene."); } } else { Debug.Log("Insufficient patrol points for basic patrolling behavior."); } SetDestination(); } }
void Start() { //Grab all waypoint objects in scene. GameObject[] AllWaypoints = GameObject.FindGameObjectsWithTag("Waypoint"); //Create a list of waypoints I can refer to later. _connections = new List <DynamicWaypoint>(); //Check if they're a connected waypoint. for (int i = 0; i < AllWaypoints.Length; i++) { DynamicWaypoint nextWaypoint = AllWaypoints[i].GetComponent <DynamicWaypoint>(); //i.e. we found a waypoint. if (nextWaypoint != null) { if (Vector3.Distance(this.transform.position, nextWaypoint.transform.position) <= _connectivityRadius && nextWaypoint != this) { _connections.Add(nextWaypoint); } } } }