x


Problem setting up an array with a size determined by a variable

I've set up an array to manage the bullets in my game. I want the amount of bullets to be varied by amountOfBullets.

Unity tells me that "An instance of type 'bulletManager' (which is the name of the script) is needed to access non-static type 'amountOfBullets'."

How do I get the arrays to be the size that i want, based on 'amountOfBullets'?

#pragma strict
// Initialise Bullets and put them in an array, along with their scripts
var bullet : GameObject;
var amountOfBullets : int = 60;
static var bullets : GameObject[] = new GameObject[amountOfBullets];
static var bulletScripts : shotScript[] = new shotScript[amountOfBullets];
more ▼

asked Jun 11 '10 at 02:29 AM

Billamu gravatar image

Billamu
277 4 6 16

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

2 answers: sort voted first

The error you're getting has nothing to do with the arrays, you just need to make your "amountOfBullets" variable static.

more ▼

answered Jun 11 '10 at 03:02 AM

qJake gravatar image

qJake
11.6k 43 78 161

Thank you for your answer.

Jun 16 '10 at 08:14 AM Billamu
(comments are locked)
10|3000 characters needed characters left

Well you have a couple of options. You could make amountOfBullets static, but I'm assuming you want it to be editable in the inspector. Another option is to delay instantiating bullets/bulletScripts until the first time bulletManager is called. I.e. do something like this:

function Awake()
{
    if( bullets == null )
    {
        bullets = new GameObject[ amountOfBullets ];
    }
}

Probably a better option is to not make bullets and bulletScripts static and instead use the singleton pattern to access your bullets and bulletScripts variables.

more ▼

answered Jun 11 '10 at 03:02 AM

Tetrad gravatar image

Tetrad
7.3k 27 37 89

Thanks. I've had to look at singleton patterns to get my head around how they work. I'm a procedural programmer and I'm having a hard time unlearning it in exchange for OOP... I'll get there :)

Jun 16 '10 at 08:14 AM Billamu
(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:

x847
x369
x284
x207
x30

asked: Jun 11 '10 at 02:29 AM

Seen: 1180 times

Last Updated: Jun 11 '10 at 02:29 AM