Null error happens even after a null check?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By IgorArts
# Character look at mouse position
if playerTarget == null:
	rayHit.y = player.translation.y
	player.look_at(rayHit, Vector3.UP)

# Character look at target
	mouseTarget = playerTarget.transform.origin
	mouseTarget.y += 1.5
	player.look_at(mouseTarget, Vector3.UP)
	gun.look_at(mouseTarget, Vector3.UP)

This is supposed to check if the mouse is pointed at an enemy. If so, player looks at enemy, if not, it just looks at the mouse position. Problem is every now and then, when testing the game, i get a null instance error after killing an enemy saying that playerTarget cant be found because its a null. Any ways to fix this?

:bust_in_silhouette: Reply From: Inces

This is the only way to check for node, that might disappear during checking or iterating.

Mind giving a sample. i tried it but gdscript cant find the function.

IgorArts | 2021-10-21 11:38

It should be is_instance_valid @GlobalScope — Godot Engine (stable) documentation in English

TheGodotPrice | 2023-07-01 17:44

:bust_in_silhouette: Reply From: TheGodotPrice

I ran into the same issue, and it went away if I used is_instance_valid instead of != null