Hi everyone ! I'm working on reproducing a tutorial for an RTS Game on Godot 4.2, but i'm also improving the code a bit. I'm trying to force static type almost everywhere, but i'm struggling with the following code :
class_name World
extends Node2D
var units: Array[Unit] = []
func _ready() -> void:
units := get_tree().get_nodes_in_group("units")
func _on_area_selected(object: Camera) -> void:
var units_selected := get_units_in_area(area)
for unit in units:
unit.set_selected(false)
for unit in units_selected:
unit.set_selected(!unit.selected)
print("Selected ", units_selected.size(), " unit", "s" if units_selected.size() > 1 else "")
func get_units_in_area(area: Array[Vector2]) -> Array[Unit]:
var units_selected: Array[Unit] = []
for unit in units:
if unit.position.x >= area[0].x and unit.position.x <= area[1].x and unit.position.y >= area[0].y and unit.position.y <= area[1].y:
units_selected.append(unit)
return units_selected
The issue is that get_nodes_in_group return an array of Node, but i expect it to return an array of Unit (which is a class, that extends CharacterBody2D, so it has a position, and my class have some methods that i call in the function _on_area_selected for example, like .set_selected()). I then have an error without even launching the game which is the following :
Value of type "Array[Node]" cannot be assigned to a variable of type "Array[Unit]"
If i only cast it like doing
func _ready() -> void:
units = get_tree().get_nodes_in_group("units") as Array[Unit]
I only have an error when the game is launched, which is the following :
Trying to assign an array of type "Array[Node]" to avariable of type "Array[Unit]"
So how can i solve this and assign the correct type ?