x


Making a GetComponent array

I am working on a projectile manager for my 2D space shooter iPhone game. And im trying at the start off the level make a array with all the ProjectileController script that is attached to the projectile gameobjects. But i get a NullReferenceException error on the line in the second for loop. How can i make this function work? Or is there a better way of achiving what im trying to do?

private var maxNumProjectiles : int = 100;
private var projectilesArray : ProjectileController[];

function InitializeProjectiles() // Initializes all the projectiles and adds their ProjectileController script to the projectilesArray
{
    for(i=0; i<maxNumProjectiles; i++)
    {
        var clone : GameObject;
        clone = Instantiate(projectilePrefab, projectileIntPosition, Quaternion.identity);
    }



var tempArray : GameObject[] = GameObject.FindGameObjectsWithTag("Projectile");



for(i=0; i<maxNumProjectiles; i++)
    {
        projectilesArray[i] = tempArray[i].GetComponent("ProjectileController");
    }
}
more ▼

asked Aug 08 '10 at 01:12 AM

Mattivc gravatar image

Mattivc
1.7k 55 60 67

Did you initialise the array?

Aug 08 '10 at 01:24 AM spinaljack

There isn't any more code concerning the array then what i posted here, so i guess not. How do i do initialize it?

Aug 08 '10 at 01:29 AM Mattivc
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

It looks like the projectilesArray is not initialized to anything, so when you try to access the i'th element it doesn't like that.

Also, you can use the "clone" return value to get the component right there, e.g.

private var maxNumProjectiles : int = 100;
private var projectilesArray : ProjectileController[];

function InitializeProjectiles() // Initializes all the projectiles and adds their ProjectileController script to the projectilesArray
{
    projectilesArray = new ProjectileController[maxNumProjectiles];
    for(i=0; i<maxNumProjectiles; i++)
    {
        var clone : GameObject;
        clone = Instantiate(projectilePrefab, projectileIntPosition, Quaternion.identity);
        projectilesArray[i] = clone.GetComponent("ProjectileController");
    }
}
more ▼

answered Aug 08 '10 at 01:30 AM

Molix gravatar image

Molix
4.8k 16 27 66

(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:

x3461
x2000
x1363
x472
x406

asked: Aug 08 '10 at 01:12 AM

Seen: 1716 times

Last Updated: Aug 08 '10 at 01:12 AM