- Home /
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];
Answer by qJake · Jun 11, 2010 at 03:02 AM
The error you're getting has nothing to do with the arrays, you just need to make your "amountOfBullets" variable static.
Answer by Tetrad · Jun 11, 2010 at 03:02 AM
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.
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 :)
Your answer
Follow this Question
Related Questions
An instance of type X is required to access non static member Y [javascript] 4 Answers
Help with Error: An instance of type 'Regex' is required to access non static member 'Replace'. 2 Answers
An instance of type "x" is required to access non-static variable "y" 2 Answers