I’m creating a 2D-Plattformer.
I have enemies with a raycast, which are always facing to the player.
Now I’m trying implementing doors in the game. The player should be able to break these doors, so if he attacks, the door get’s the ‘queue_free()’ command.
It works okay, but if a enemy raycast is hitting the door and it gets destroyed, the game crashes with the error: “Attempt to call function ‘is_in_group’ in base ‘null instance’ on a null instance”.
I can’t get to any solution, does someone have an idea?
This is the code related to the error:
#Gun_shooting & checking
if target != null:
var angle_to_target: float = global_position.direction_to(target.global_position).angle()
rayCast.global_rotation = angle_to_target
if rayCast.is_colliding() and rayCast.get_collider().is_in_group("Player"):
gunSprite.rotation = angle_to_target
if reloadTimer.is_stopped():
shoot()
RayCast2D calculates intersection every physics frame, and it holds the result until the next physics frame. For an immediate raycast, or if you want to configure a RayCast2D multiple times within the same physics frame, use force_raycast_update.
I’m guessing that either you’re checking the raycast result outside of _physics_process or in the same _physics_process as you free the doors (after they are freed). I’m not sure if rayCast.get_collider then returns null or or it returns a freed object, but I think you just need to check that rayCast.get_collider() isn’t null before using it. If a not null check fails then there’s also a @GlobalScope function calls is_instance_valid which you could try instead (I don’t know much about Godot’s Node lifecycle yet, maybe I’ll learn something from this thread).
I’m checking the rayCast inside of the _physics_process
I checked if the rayCast collider is null, before the code.
It works now.
I’ve tried to do the same before but with “rayCast.is_colliding()” which unfortunately didn’t work.
So if I understand it correctly, when i free the door, the raycast will hold the result up until the next frame, which means it crashes because he still thinks that the door’s there.
Here’s the code solved:
if rayCast.get_collider() != null:
if rayCast.is_colliding() and rayCast.get_collider().is_in_group("Player"):
gunSprite.rotation = angle_to_target
if reloadTimer.is_stopped():
shoot()