- Home /
Giving the player ammo
Hi, I have a script called "Stats" that setups the games variable such as the health, ammo, etc. The script:
static var statHP : float = 100;
static var statMaxHP : float = 100;
static var gunAmmo = new Array();
function Awake(){
gunAmmo[0] = 10;
gunAmmo[1] = 50;
}
I'm not sure if I set up the array correctly... Anyway, before creating/firing a bullet, I check the ammo count for the current weapon. Each weapon has a variable gun which I use to check the ammo count. The script for creating the bullet(just a part):
if (Input.GetButton("Fire1") && Stats.gunAmmo[gun] > 0 && timer == 0){
Instantiate(bullet,transform.TransformPoint(Vector3(0,0,zOff)),transform.rotation);
Instantiate(gunfire,transform.TransformPoint(Vector3(0,0,zOff)),transform.rotation);
timer = wait;
Stats.gunAmmo[gun] --;
}
I use that and I get the error:
Assets/Scripts/Create bullet.js(12,30): BCE0049: Expression 'Stats.gunAmmo.get_Item(self.gun)' cannot be assigned to.
So I'm guessing either you can't do anything with arrays outside of the script that contains it, or I created the array incorrectly. Could any help me please?
Answer by flaviusxvii · Jun 27, 2011 at 09:40 PM
http://unity3d.com/support/documentation/ScriptReference/Array.html
Did you give your array a size (or length)?
I've tried putting gunAmmo.length = 2; inside Awake, but it still gave me the same error.
Hmm.. maybe this would be better.
static var gunAmmo = new int[2];
It doesn't give me an error or anything, but now for some reason the weapon doesn't create/fire bullets anymore... I'm assu$$anonymous$$g this is how I should set it up?
static var gunAmmo = new int[2];
function Awake(){
gunAmmo[0] = 10; gunAmmo[1] = 50; }
That looks good, so I don't think the issue is your array anymore.
Side note: Tracking ammo in a global variable is a little strange. Wouldn't it make more sense to have a "Gun" component with ammo as a datamember?
So it may just be my firing script? I'll go mess around with it.
I'm used to using arrays/global variables for ammo and stats, plus I'm needing to save and load the variables, so I'll be using global variables for now.
EDIT: By datamember I'm assu$$anonymous$$g variables in scripts(var blah : int;) right?
Answer by Ludiares.du · Jun 27, 2011 at 09:52 PM
Try setting
gunAmmo = new Array();
in the awake function.
Something like:
function Awake(){
gunAmmo = new Array();
gunAmmo[0] = 10;
gunAmmo[1] = 50;
}
Doing that I get the error: Assets/Scripts/Create bullet.js(8,47): BCE0019: 'gunAmmo' is not a member of 'Stats'.
Your answer