Godot Version
4.6
Question
I have an enemy class, which has very basic pathfinding. It is supposed to find the first character inside of the group “Characters”, using the variable direction and direction to, set its velocity towards the player. I also have a character class, which adds itself to the “Characters” group on ready. However, the enemy class returns the character as nil as soon as i start the game. The pathfinding used to work when i tested it at first, but after i made it so that the enemy tracks specifically the first node in “Characters”, it keeps returning nill and i dont know how to fix it. I even tried manually assigning the character to the group Characters without much luck. Here is the code of the enemy:
I have a seperate scene for character selection, so that might be causing the issue. i also have a game manager script. I’ll add that too
class_name Enemy
extends CharacterBody2D
# Variables
@export var animatedSprite : AnimatedSprite2D
@export var hitboxComponent : HitboxComponent
@export var hitboxShape : CollisionShape2D
@export var attackArea : Area2D
@onready var character = get_tree().get_first_node_in_group("Characters")
@export var moveSpeed := 100
# States
enum States {IDLE, RUNNING, ATTACKING}
var currentState := States.RUNNING
func _ready() -> void:
animatedSprite.animation_finished.connect(on_animation_finished)
func _physics_process(delta: float) -> void:
move_towards_character()
func move_towards_character():
if character:
var direction = global_position.direction_to(character.global_position)
velocity = direction * moveSpeed
move_and_slide()
func handle_animations():
if currentState == States.RUNNING:
animatedSprite.play("Run")
# Sprite Flipping
if character.global_position < global_position:
animatedSprite.flip_h = false
elif character.global_position > global_position:
animatedSprite.flip_h = true
func on_animation_finished():
currentState = States.IDLE
extends Node2D
@onready var spawnPosition: Marker2D = $SpawnPosition
func _ready() → void:
var character = CharacterSelector.selectedCharacter.instantiate()
add_child(character)
character.global_position = spawnPosition.global_position