public ConnectedWaypoints NextWaypoint(ConnectedWaypoints previousWaypoint) { if (_connections.Count == 0) { //no waypoint? return null Debug.LogError("no waypoints count."); return(null); } else if (_connections.Count == 1 && _connections.Contains(previousWaypoint)) { //only 1 waypoint and its where we just were? use it return(previousWaypoint); } else // or else find a random one that isnt the last one we were at { ConnectedWaypoints nextWaypoint; int nextIndex = 0; do { nextIndex = UnityEngine.Random.Range(0, _connections.Count); nextWaypoint = _connections[nextIndex]; } while (nextWaypoint == previousWaypoint); return(nextWaypoint); } }
private void SetDestination() { if (_waypointVisited > 0) { //find next waypoint ConnectedWaypoints nextWayponit = _currentWaypoint.NextWaypoint(_previousWaypoint); _previousWaypoint = _currentWaypoint; _currentWaypoint = nextWayponit; } Vector3 targetVector = _currentWaypoint.transform.position; _navMeshAgent.SetDestination(targetVector); _traveling = true; }
//initilization public void Start() { _navMeshAgent = this.GetComponent <NavMeshAgent>(); if (_navMeshAgent == null) { Debug.LogError("the nav mesh agent is not attached to " + gameObject.name); } else { if (_currentWaypoint == null) { //set renadom //grab all waypoint objects GameObject[] allWaypoints = GameObject.FindGameObjectsWithTag("Waypoint"); if (allWaypoints.Length > 0) { while (_currentWaypoint == null) { int random = UnityEngine.Random.Range(0, allWaypoints.Length); ConnectedWaypoints startingWaypoint = allWaypoints[random].GetComponent <ConnectedWaypoints>(); //i.e. we found waypoint if (startingWaypoint != null) { _currentWaypoint = startingWaypoint; } } } else { Debug.LogError("failed to find any waypoints to use in the scene"); } } SetDestination(); } }
public void Start() { //get all waypoints in scene GameObject[] allWayPoints = GameObject.FindGameObjectsWithTag("Waypoint"); //create list _connections = new List <ConnectedWaypoints>(); //check if connected for (int i = 0; i < allWayPoints.Length; i++) { ConnectedWaypoints nextWaypoint = allWayPoints[i].GetComponent <ConnectedWaypoints>(); //found waypoint? if (nextWaypoint != null) { if (Vector3.Distance(this.transform.position, nextWaypoint.transform.position) <= _connectivityRadius && nextWaypoint != this) { _connections.Add(nextWaypoint); } } } }