This bit of code does exactly what i want, but throws an error. What should i do instead?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By LucasFLavra
func shoot():
if not get_parent().get_node("Laser"): 
	var laser = laser_scn.instantiate()
	laser.position.x = position.x
	laser.position.y = position.y - 16
	add_sibling(laser)

player.gd:30 @ shoot(): Node not found: “Laser” (relative to “/root/Main”).

:bust_in_silhouette: Reply From: jgodfrey

The problem here is that when the Laser node doesn’t exist, that get_node() call returns null. When that happens, you’re then trying to ask for the parent of a null node, which doesn’t make sense and generates the error.

There are likely better ways to solve this, but an easy way would be something like:

if not get_node("../Laser"):
:bust_in_silhouette: Reply From: aidave

Use get_node_or_null() instead, when you aren’t sure if the node exists or not.

Or even better for this case, is has_node() since you aren’t using the return value

Perfect!

Thank you for your time.

LucasFLavra | 2023-03-14 18:12