x


Array of GameObjects

Hi All.

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[i] as GameObject; // THIS MAKES ERROR
    var ballVector : Vector3 = (ball.transform.position);
}

return null;

}

The error I'm getting is: NullReferenceException: Object reference not set to an instance of an object

What am I doing wrong? What is the correct way to store an array of GameObjects?

Thanks, Jonas

more ▼

asked Apr 09 '10 at 09:21 AM

Jonas gravatar image

Jonas
103 3 3 12

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

Problem is solved. Answer can be found at http://forum.unity3d.com/viewtopic.php?t=49078

In short, here is the code:

var balls : ArrayList; 

function Start() { balls = new ArrayList();

// Instantiate ball for test-purpose var newBall = Instantiate(ballPrefab,Vector3(10.0,0.0,10.0),Quaternion.identity); balls.Add(newBall.gameObject); // Notice .gameObject }

function findClosestBall(ball_x : int, ball_y : int) : GameObject {

var closestBall : GameObject; var shortestDistance : float = 9999; var ballPos : Vector3; var coordinatePos : Vector3; var distanceVector : Vector3;

for(var ball : GameObject in balls){ ballPos = ball.transform.position; coordinatePos = Vector3(ball_x, GameController.y_height, ball_y); distanceVector = ballPos - coordinatePos;

  if (distanceVector.magnitude < shortestDistance){ 
     closestBall = ball; 
     shortestDistance = distanceVector.magnitude; 
  } 

} return closestBall; }

more ▼

answered Apr 15 '10 at 09:15 AM

Jonas gravatar image

Jonas
103 3 3 12

(comments are locked)
10|3000 characters needed characters left

your for statement has an error. It says:

for (var i=0; balls.length; i++) {

when it should say:

for (var i=0; i < balls.length; i++){
more ▼

answered Apr 09 '10 at 09:55 AM

duck gravatar image

duck ♦♦
41k 92 148 415

Yeah of course. That's not the error though.

Apr 09 '10 at 10:37 AM Jonas
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x2086
x1360
x1093
x520
x9

asked: Apr 09 '10 at 09:21 AM

Seen: 21955 times

Last Updated: Apr 09 '10 at 09:21 AM