How can I make the script to pick another object after one gets deleted

Godot Version

4.3

Question

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

here is the code pls look
Before the collision

After, The collision

How can I make the script to pick another potion after one gets deleted?

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.

( p stand for potion)
how can I change it another potion?

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.

Can you give an outline on how to do that? sry,I am new to gdscript and godot

Click on the potion node(s) and select them (one at a time) , go to the “node” tab (it’s next to the inspector tab)


click on groups and then the plus button

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.

THANK YOU, its working

1 Like