So I have a player and I create three potions(they are a scene) at random positions across the whole main game scene. Now I want the player to find all the three potions but it hard to find without a hint so to give hint to the player I decided to have a label which indicates the nearest potion. When the player collides with the potion the potion gets deleted but it suddenly gets the game crash, I cant understand why
I think it’s because p refers to the potion that was freed. Either check if is_instance_valid() before trying to get its global position, or change p to something else when the potion is freed.
You need to get a reference to the potion. One way is using NodePath, but i think in your case you should put all the potions into a group and iterate through them to see which potion is the closest to the player.
add a new group (it doesn’t matter if it’s global or not)
in your script, add code like this
func _process(delta):
longDistance = null
for p in get_tree().get_nodes_in_group("potion"):
var distance = player.global_position.distance_to(p.global_position)
if not longDistance or longDistance > distance:
longDistance = distance
$Control/ShortestDistancePath.text = str(longDistance)
It’s just getting all the nodes in the group and iterating through them. It only works if the group is called “potion” exactly, with the same capitalization.