Why is it required to check a body's group before accessing its variable?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Trifle0655

I have the following code:

func _on_Area2D_body_entered(body):
	if !body.is_in_group("Player"):
	if body.relationship > 0:
	target = body

func _on_Area2D_body_exited(body):
	target = null

Which works fine, my enemy starts chasing the player if they’re in range nad their relationship is low.

It doesn’t work when I don’t have the is_in_group() segment, why? How does it affect whether or not the area2d can get my body’s variable?

:bust_in_silhouette: Reply From: jgodfrey

I assume the relationship property only exists on the Player node. So, if the _on_Area2D_body_entered() method is triggered by something other than the Player, the code will fail when trying to access the relationship property of that (non-Player) node.

So, it’s checking that the body in question really IS the Player first. If not, it simply returns.

That could be rewritten to make the intent a bit clearer. Something like this:

func _on_Area2D_body_entered(body):
    if body.is_in_group("Player") and body.relationship == 0:
        target = body

That should be functionally the same as the original code, but (potentially) easier to understand.