how to "invalid get index "global_position"(on base:"previously freed instance")"

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

const MOVE_SPEED = 400

onready var raycast = $RayCast2D

var player = null

func _ready():

func _physics_process(delta):
if player == null:

var vec_to_player = player.global_position - global_position
vec_to_player = vec_to_player.normalized()
global_rotation = atan2(vec_to_player.y, vec_to_player.x)
move_and_collide(vec_to_player * MOVE_SPEED * delta)

if raycast.is_colliding():
	var coll = raycast.get_collider()
	if == "komble":

func kill():

func set_player(p):
player = p

this is my enemy code and when player dies game crushe. help me!

:bust_in_silhouette: Reply From: Zylann

This happens because you are litterally destroying the player node, and you still try to access its global_position later. Accessing a destroyed node will cause your game to stop working.

You can solve this in several ways. The safest is to set the player variable to null after you kill it, because for technical and performance reasons, destroying a node will not set all its references in the world back to null, you have to do this yourself.
So next time you can do if player != null before trying to access it again. If the player respawns, assign the player variable back, or reload the scene.

Another way is to store the path to the player node instead of the player directly. You can then access the player by using get_node(player_path) and check if it exists by doing has_node(player_path).

Yet another way is to put the player in a “player” group, so you can access it using get_nodes_in_group("player") and you won’t need to store it in a variable. If no players are in the group, you know it has been destroyed.

And again another way is to check is_instance_valid(player) instead of null, however this is not guaranteed to work in Godot 3.2 due to a bug which will be solved in Godot 4.0.

Can you help me to solve this problem? How can i solve this with first way? I am begginer.

Sandro | 2020-05-14 11:30

if raycast.is_colliding():
    var coll = raycast.get_collider()
    if == "komble":
        # Assuming you destroy the player node inside `kill()`
        # If that was the player
        if coll == player:
        	# Set ref to null
        	player = null
        	print("I killed the player")

Make sure the print works, I haven’t tested this code

Zylann | 2020-05-14 12:08