basic array creation

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By GarrettGemini

I’m coming from a C & VB6 background and don’t understand array creation and use in godot 3.0. I’ve read the article on moving over from static languages to dynamic languages, but it wasn’t much help, and I searched for basic syntax and examples and have been coming up short.

Here’s an example of what I’m trying to do.
my player has a weapon that has upgrades to it, we’ll say there are 6 levels. These levels change the fire rate and the range of the weapon.

In my older languages I would create a datatype of what I wanted like

Type weaponUpgrades
     range as single
     fireRate as single

Then I could declare an array using my datatype

dim myGun( 6 ) as weaponsUpgrade

then I could access what I set the various values to by:

myWeaponLevel = 2
playerShootSpeed = myGun( myWeaponLevel ).fireRate

It seems absurd to me that I have to ask for help on something as simple as creating an array, but here we are so I appreciate any help I can get.


:bust_in_silhouette: Reply From: kidscancode

In GDScript (and Python) you would use a dictionary for this. Dictionaries are key/value stores, somewhat like struct in a C-type language.

So you could make a dictionary to hold the various gun levels:

myGun = {}
myGun[1] = {"range": 100,
            "fireRate": 10}
myGun[2] = {"range": 200,
            "fireRate": 25}

And then you would access it by:

myWeaponLevel = 2
playerShootSpeed = myGun[myWeaponLevel]["fireRate"]

Note: I’m using your variable names, although GDScript style is snake_case.

There’s lots of good info on arrays and dictionaries in the docs:

Thank you for answering. I believe its one of your tutorials on youtube that I was following that got me this far. “space rocks” I have deviated from the tutorials, maybe a little prematurely. haha.

Anyway, this did not work for me.

myGun = {}
myGun[1] = {"range": 100,
            "fireRate": 10}
myGun[2] = {"range": 200,
            "fireRate": 25}

returns error “Unexpected token: identifier: myGun”
I made it:
var myGun = {}
but that just moved the error down to the myGun[1] = …

again, im not finding much documentation on that error, but i will be reading up on dictionary creation, but if you have any idea on the problem please let me know.


GarrettGemini | 2018-04-08 09:34

Ok, I think I found that if I put the declarations into the _ready() function it doesn’t give me the error. I haven’t tried to use the variables yet, but hopefully that does the trick. Not ideal, but I can work with that.

Thank you for all your help kidscancode!!


GarrettGemini | 2018-04-08 11:44