very simple script but I am new to this. could someone just tell me what im doing wrong. im getting this in the console and of course not getting any results Field `Nav.bestTarget' is never assigned to, and will always have its default value `null' Code (CSharp): public class Nav : MonoBehaviour { NavMeshAgent agent; Transform bestTarget; public GameObject[] trees; void Start () { agent = GetComponent<NavMeshAgent> (); } // Update is called once per frame void Update () { trees = GameObject.FindGameObjectsWithTag ("tree"); agent.SetDestination (bestTarget.position); } Transform GetClosestTree ( GameObject[] trees) { Transform bestTarget = null; float closestDistanceSqr = Mathf.Infinity; Vector3 currentPosition = transform.position; foreach(GameObject potentialTarget in trees) { Vector3 directionToTarget = potentialTarget.transform.position - currentPosition; float dSqrToTarget = directionToTarget.sqrMagnitude; if(dSqrToTarget < closestDistanceSqr) { closestDistanceSqr = dSqrToTarget; bestTarget = potentialTarget.transform; } } return bestTarget; } }
im trying to get the character to move to the closest tree out of the trees array, and ive scrapped this script together and just needed some assistance
Haven't checked it but try this Code (CSharp): public class Nav : MonoBehaviour { NavMeshAgent agent; Transform bestTarget; public GameObject[] trees; void Start () { agent = GetComponent<NavMeshAgent> (); } // Update is called once per frame void Update () { trees = GameObject.FindGameObjectsWithTag ("tree"); bestTarget=GetClosestTree (trees) agent.SetDestination (bestTarget.position); } Transform GetClosestTree ( GameObject[] trees) { Transform result = null; float closestDistanceSqr = Mathf.Infinity; Vector3 currentPosition = transform.position; foreach(GameObject potentialTarget in trees) { Vector3 directionToTarget = potentialTarget.transform.position - currentPosition; float dSqrToTarget = directionToTarget.sqrMagnitude; if(dSqrToTarget < closestDistanceSqr) { closestDistanceSqr = dSqrToTarget; result = potentialTarget.transform; } } return result; } }