I'm having some trouble adding and especially retrieving GameObjects from an array.
Here is a code sample:
var balls = new Array();
function Start()
{
// Instantiate ball for test-purpose
var newBall : GameObject = GameObject.Instantiate(ballPrefab,Vector3(10.0,0.0,10.0),Quaternion.identity) as GameObject;
balls.Add(newBall);
}
function findClosestBall(ball_x : int, ball_y : int) : GameObject {
for (var i=0; balls.length; i++){
var ball : GameObject = balls *as GameObject; // THIS MAKES ERROR*
*var ballVector : Vector3 = (ball.transform.position);*
*}*
*return null;*
*```*
*<p>}</p>*
*<p>The error I'm getting is:*
*<em>NullReferenceException: Object reference not set to an instance of an object</em></p>*
*<p>What am I doing wrong? What is the correct way to store an array of GameObjects?</p>*
*<p>Thanks,*
*Jonas</p>*
No, he’s right. That would cause the error. If balls.length is not zero, that expression evaluates to true, no matter what iteration you’re on. You’ll eventually hit the end of the array and be out of objects, hence the null reference.