invalid call. Nonexistent function 'filter ' in base 'CharacterBody2D()'

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

Hi, I am working on a 2D game
I encountered this problem and I do not know how to solve it … Please help me, as my experience in the godot engine is not great

this is the code of my enemy >>

extends Node
const MAX_RANGE = 150
@export var sword_ability : PackedScene
# Called when the node enters the scene tree for the first time.

func _ready():

func on_timer_timeout():
	var player = get_tree().get_first_node_in_group("player") as Node2D
	if player ==null:

	var enemies = get_tree().get_first_node_in_group("enemy")
	enemies = enemies.filter(func(enemy:Node2D):
		return enemy.global_position.distance_squared_to(player.global_position) < pow(MAX_RANGE,2))
	if enemies.size() == 0:
	enemies.sort_custom(func(a: Node2D, b:Node2D):
		var a_distance = a.global_position.distance_squared_to(player.global_position)
		var b_distance = b.global_position.distance_squared_to(player.global_position)
		return a_distance < b_distance
	var sword_instance = sword_ability.instantiate() as Node2D
	sword_instance.global_position = enemies[0].global_position

There is no text error in the code, but I don’t know where the problem is!..HELP ME

Instead of var enemies = get_tree().get_first_node_in_group("enemy") shouldn’t it be var enemies = get_tree().get_nodes_in_group("enemy")? Since you want to filter an array of the nodes contained in the group "enemy"

Joel Gomes da Silva | 2023-07-05 16:41

@alhoot Edited to format the code. Use the Code Sample button.

Zylann | 2023-07-05 17:04

Its wooorking
thank you

alhoot | 2023-07-05 18:19

:bust_in_silhouette: Reply From: Zylann
var enemies = get_tree().get_first_node_in_group("enemy")

get_first_node_in_group will return the first node found in the "enemy" group. So it returns a node, not an array.
filter is a function of Array: Array — Godot Engine (stable) documentation in English

Therefore when you do enemies.filter( it won’t work since enemies is not an array.

As proposed, since you thought it was an array, perhaps you meant to write this instead:

var enemies = get_tree().get_nodes_in_group("enemy")

Which will return an array of all the enemies, which you can use filter on.

Not every error can be determined before you run the game, as you write the code, because GDScript is a dynamic language.
Usually when such errors occur when the game runs, Godot will stop at a breakpoint in the editor, where you can inspect what each variable contains. This can help to verify if your variables contain what you expect.

Its wooooooooooorking
Your answer is simple and wonderful
Thank you a lot

alhoot | 2023-07-05 18:17