Null instance when interacting with objects using a Raycast2D

Godot Version

4.2.2

Question

i am using a Raycast2D to interact with objects in my level. Whenever the raycast hits a target that is interactable its put a picture to show players what key to press to interact with it. However when I press the interact button on an item, the item is deleted via queue_free() but the method stops working because it no longer detects the object that it is detecting giving me a null instance and crashing the game.

Here is the code that is giving me the error. Its currently put in the process function. ignore the commented out section. It was there to fix another issue that I can’t remember in the past that I’m trying to see if I still need it

func InteractRay():
	var object
	if interactRay.is_colliding():
		#if interactRay.get_collider().get_parent().is_in_group("Item"):
			#object = interactRay.get_collider()
			#interactRay.add_exception(object)
			#object=null
			#print("i have added to excpetion")
			
		object = interactRay.get_collider()
		if object.get_parent().has_method("Interact") or object.has_method("Interact"):
			e_interact_picture.visible = true
			object=null
	else:
		e_interact_picture.visible = false
		object = null

I’m tried putting object = null so that the method hopefully stops trying to detect something when it get deleted but that hasn’t worked.

Either make sure the raycast is updated (call interactRay.force_raycast_update() at the beginning of the function) or check is_instance_valid(object) before calling any of the object’s functions.

Raycasts are updated once per physics frame. If the collider got freed between the last update and this code, is_colliding() will still be true, even though the collider doesn’t exist anymore.

Thank you so much! You have solved my problem