Skip to main content

Recasting Typed Arrays in GDScript

·212 words·1 min

Casting an array to a different type in Godot.

get_children() returns an Array[Node] but I want to store it as an array of flowers, which are a subclass of Node.

What I wanted to do:

var flowers: Array[Flower] = get_children() as Array[Flower]

But Godot gives an error.

Trying to assign an array of type "Array[Node]" to a variable of type "Array[Flower]".

The solution from kleonc is to use Array.assign(). https://www.reddit.com/r/godot/comments/12dm8i2/how_to_cast_an_array_to_a_more_concrete_class_in/

var flowers: Array[Flower]
flowers.assign(get_children())

A little clunky but at least it’s concise.

#

Main

  • Level
    • Flower
      • Pollen
    • Flower
      • Pollen
      • Pollen
    • Flower
      • Pollen
    • Player

Player emits gather_attempted. Level catches it and tells whatever flower the player is currently sitting on. Flower checks distance to pollen and if close enough, emits gathered. Level catches gathered and emits another event (name?). Main catches that and draws the pollen nugget going to the counter and increments the counter.

This seems okay but the silly bit is that Level catches an event and basically propagates it up the tree. Is there a way to have Godot just propagate events up the tree? Isn’t that how the InputEvents work already?

Another possibility:

Player emits gather_attempted and all flowers catch it… nah.

Player emits gather_attempted and—

EventBus? To go directly from Flower to Main? Or even Flower to HUD?