#Array and dictionary wackiness

4 messages · Page 1 of 1 (latest)

wicked narwhal
#

Hello B)

Im trying to set up at script that by itself finds out what type of fish (in this case swimmer) it is and assigns its own speed and value accordingly. Unfortunately it seems that my process to grab a specific key from the array is wrong but im not actually sure how to fix it

var swimmer_types = [
    {"name" : "orange fish", "speed" : 5, "points" : 1},
    {"name" : "red fish", "speed" : 10, "points" : 2},
    {"name" : "trash", "speed" : 3, "points" : -1}
]

var my_points : int = 0
var my_speed : float = 0

# Called when the node enters the scene tree for the first time.
func _ready():
    _assign_type()
    pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):


func _assign_type() -> Array:
    for type in swimmer_types:
        if self.is_in_group(swimmer_types[type]["name"]): <-error is here?
            my_points = type["points"]
            my_speed = type["speed"]
    return [my_speed, my_points]


func _on_area_2d_body_entered(body):
    if body.is_in_group("player"):
        print(my_points, my_speed)```

if clarification or more details are needed let me know
tame ridge
#

Try printing the values you get in the loop in _assign_type - what does print(type) give you? and print(swmmer_types[type])?

#

A more specific explanation (I recommend you try debugging some more and only then read it) - ||for loops don't give you the indexes of the array, they give you the items in the array. So in your case, type is already the dictionary, so you just need type[name] - swimmer_type[i]["name"] would work if i was a number, but you don't need it, since type already contains what you wanted||

#

Also, not relevant to the specific issue, but it might be nice for your code - I recommend using resources, instead of dictionaries+groups.
That way you can have an @export var swimmer_type: SwimmerType, and then drag and drop the swimmer type in the editor, and define the speed and points there as well, alongside a texture.
Then you don't even need the group and the dictionary lookup, since swimmer_type contains everything that you need 🙂

I haven't watched it fully, but from short skimming, this seems to explain the concept - https://www.youtube.com/watch?v=h5vpjCDNa-w

This video gives a quick overview of how you can use Resources in Godot 4, and how to create your own custom Resources.

Resources are a very handy way to handle bundles of data and code. They can be saved to disk and loaded by other objects in the project. This makes it super handy to swap in and out functionality as needed.

Project Link:
GDSc...

▶ Play video