Cant get global position of my player anymore

Godot Version



Im trying to make some changes to my pathfinding since it seems to cause lag spikes. After changing the Pathfinding code i suddenly wasnt able to get the player position and now i get this error : “Invalid get index ‘global_position’ " (on base: ‘Nil’)”

extends CharacterBody2D

@export var speed = 100
@onready var player = get_tree().get_first_node_in_group("player")
@onready var anim = $AnimatedSprite2D
@onready var gamemode2 = get_node("/root/Gamemode2")
var KrabHealth = 100
var in_range = false
var AttackCooldown = true

var money = preload("res://Scenes/item_money.tscn")
var HealthBrew = preload("res://Scenes/health_brew.tscn")
signal enemy_died

@export var coin_amount = 1

@onready var navigation_agent: NavigationAgent2D = $NavigationAgent2D

var movement_speed: float = 200.0
var movement_target_position = player.global_position
@onready var player = get_tree().get_first_node_in_group("player")
var movement_target_position = player.global_position

What’s happening is that you are setting the player variable to the player when _ready() is called, be setting the movement_target_position to the player variable’s global position before the player variable is set to the player. Because the variable is nil by default, the engine can’t find a property named global_position on a base instance of nil. Try putting the @onready export before defining movement_target_position.

1 Like

Its means your player is no more, have you do somewhere that player.queue_free()?

Yeah, I wonder if you even need to initialize the variable there, or if that would make more sense in a function that’s updated every frame. Wouldn’t the player position be constantly changing?

Yes. As far as I know, you can’t link variables, so declare the variable but don’t assign it. Then, only assign it in _process() or _physics_process as the first line.

1 Like