Find a property in an array of dictionaries

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

So in my game server, I have an array of players. Each player is a dictionary, for example:

var players = [{ "name": "Mark", "position": 10 }, { "name": "Frank", "position": 2 }]

Now, I’d like to interpolate the position properties of the players, I tried this:

$Tween.interpolate_property(self, "players:0:position", players[0].position, 20, 0.2)
$Tween.start()

But Godot throws an error saying that it can’t find the node. Is there any way to find the index of the array in a NodePath?

:bust_in_silhouette: Reply From: Ninfur

The first argument is the target object, which should be players[0] in your example, and the second argument is the key of the property on that object. I’m unsure if dictionary entries count as “properties”, but if they do you can try something like this:

$Tween.interpolate_property(players[0], "position", players[0].position, 20, 0.2)

Sadly Godot doesn’t count it as an object: when I run the code it says

Invalid type in function 'interpolate_property' in base 'Tween'. Cannot convert argument 1 from Dictionary to Object.

It did work in Godot 2 as far as I know though

VitusVeit | 2022-10-27 21:06

Hm, alright. According to this reddit thread it might be possible with colon separation if the dictionary is a variable on the target object, like you tried. But I’m not sure if that is possible with the dictionary inside an array. Perhaps changing ‘players’ to a dictionary too, could work?

Ninfur | 2022-10-27 21:14

You’re right, it should work with a dictionary inside a dictionary. But I don’t know if it would work for loops. Anyway, I’ll give it a look tomorrow, thanks.

VitusVeit | 2022-10-27 21:29

For looping I think you can do something like:

for key in players_map:
    $Tween.interpolate_property(self, "players:" + key + ":position", players_map[key].position, 20, 0.2)

Assuming nested dictionaries.

Another alternative could be to create a custom class for the player info, rather than using a dictionary. That way you can send the player info object as “target object” to the tween.

Ninfur | 2022-10-28 05:35

I tried the dictionary in a dictionary solution and it worked, thank you!

VitusVeit | 2022-10-28 18:28