Null instance from global_position

v4.2.2.stable.official [15073afe3]

I am working on my first game and I am working on a follow state for my finite state machine.

I have an enemy skeleton as a CharacterBody2D node named “skeletonEnemy” and a player character as a CharacterBody2D node named “player”.

My code is as follows.

 extends State
    class_name EnemeyFollow
    @export var enemy: CharacterBody2D
    @export var targetName:=""
    var followTarget: CharacterBody2D
    var move_speed = 100
    var move_direction : Vector2
    @export var followRadius:=25
    func Enter():
    	followTarget = get_tree().get_first_node_in_group(targetName)
    	print("Target is ",targetName)
    	move_speed = enemy.base_speed
    	#print(move_speed," is idle movespeed.")
    func Update(_delta):
    func Physics_Update(_delta):
    	move_direction = followTarget.global_position - enemy.global_position
    	if move_direction.length() > followRadius:
    		enemy.velocity = move_direction.normalized() * move_speed
    		enemy.velocity = Vector2.ZERO

When I run my tester scene with the target set to “player” I get the following error.

Invalid get index 'global_position'(on base:'null instance').    

From what I can understand, the line of code setting the followTarget CharacterBody2D is returning <Object#null> instead of the player CharacterBody2D.

I’m unsure how to set the followTarget to the player CharacterBody2D. Does anyone have any suggestions or know why I am not getting the correct assignment for followTarget?

This function returns null if not found

And also is using the group system of Godot.

Is “player” a group?

Was player added to the player group?

@pennyloafers is correct that the get_first_node_in_group function will return null if no nodes are found in that group.

You may be using the function incorrectly… it searches for a node tagged under a given group, not a node that has a given name as implied in the variable named targetName. You can check the documentation for groups that @pennyloafers linked in their post.

Are you sure that the Enter function is getting called? If it is not, then regardless of how your groups are set up, followTarget will not be assigned the correct value.