I’m a little stuck here, I’m getting an error … “NullReferenceException: Object reference not set to an instance of an object” on the line 29
var diff = (closestCar*.transform.position - player.transform.position);*
The Start function works fine as I’ve debugged it and passes the found Car GameOjects and prints them out.
private var player : GameObject;
private var theClosestCar : GameObject;
private var gameObjects : GameObject[];
private var closestCar : GameObject[] = new GameObject[10];
private var k : int;
function Start(){
// Find the Player
- player = GameObject.Find(“First Person Controller”);*
// Search through all GameObjects in the hierarchy for ALL the Cars
- gameObjects = FindObjectsOfType(GameObject) as GameObject;*
- for (var i=0; i < gameObjects.length; i++){*
_ if(gameObjects*.name.Contains(“Car Type”)){_
_ closestCar[k] = gameObjects; // Pass the found Car to the closestCar array*
* k++;
}
}
}*_
function FixedUpdate(){
* Debug.Log(FindClosestCar().name);*
}
// Find the closest Car
function FindClosestCar() : GameObject {
* var distance = Mathf.Infinity;*
* for (var i=0; i < closestCar.length; i++){*
_ var diff = (closestCar*.transform.position - player.transform.position);
var curDistance = diff.sqrMagnitude;*_
* if (curDistance < distance) {*
_ theClosestCar = closestCar*;
distance = curDistance;
}
}
return theClosestCar;
}*_