public ConnectedWayPoint NextWayPoint(ConnectedWayPoint previousWayPoint) { if (_connections.Count == 0) { Debug.LogError("Insufficient waypoint count."); return(null); } else if (_connections.Count == 1 && _connections.Contains(previousWayPoint)) { return(previousWayPoint); } else { ConnectedWayPoint 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) { ConnectedWayPoint nextWaypoint = _currentWaypoint.NextWaypoint(_previousWaypoint); _previousWaypoint = _currentWaypoint; _currentWaypoint = nextWaypoint; } Vector3 targetVector = _currentWaypoint.transform.position; _navMeshAgent.SetDestination(targetVector); _travelling = true; }
// Use this for initialization public void Start() { GameObject[] allWaypoints = GameObject.FindGameObjectsWithTag("WayPoint"); _connections = new List <ConnectedWayPoint> (); for (int i = 0; i < allWaypoints.Length; i++) { ConnectedWayPoint nextWayPoint = allWaypoints [i].GetComponent <ConnectedWayPoint> (); if (nextWayPoint != null) { if (Vector3.Distance(this.transform.position, nextWayPoint.transform.position) <= _connectivityRadius && nextWayPoint != this) { _connections.Add(nextWayPoint); } } } }
// Use this for initialization public 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) { GameObject[] allWaypoints = GameObject.FindGameObjectsWithTag("Waypoint"); if (allWaypoints.Length > 0) { while (_currentWaypoint == null) { int random = UnityEngine.Random.Range(0, allWaypoints.Length); ConnectedWayPoint startingWaypoint = allWaypoints[random].GetComponent <ConnectedWayPoint>(); if (startingWaypoint != null) { _currentWaypoint = startingWaypoint; } } } else { Debug.LogError("Failed to find any waypoints for use in the scene."); } } SetDestination(); } }