check if get_collider() has more than 0 entities?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Robster
:warning: Old Version Published before Godot 3 was released.

Hi all,

I’m doing this:

var entity = ball.get_collider()
if entity.get_name() == "bat":
    #do stuff

and on this line if entity.get_name() == "bat": I’m getting this error:
Invalid call. Nonexistent function 'get_name' in base 'Nil'.

So I’m assuming that entity doesn’t have anything in it. I find that strange though as it only comes into play AFTER the if statement. So how can that be?

I must be doing something wrong so I’m hoping someone can shed some fresh eyes on this for me.

Thanks so much…

:bust_in_silhouette: Reply From: cardoso

You can use is_colliding() before that code. If that is true, then there is a collider.

Like this:

if ball.is_colliding():
    var entity = ball.get_collider()
    if entity.get_name() == "bat":
    #do stuff

A quick thing I noticed! Looks like there still might be a change is_colliding() is true and get_collider() is null. It seems to happen sometimes if the body (ball in your case) is destroyed using queue_free() somewhere.

I am just using another condition, is get_collider(), and so far seems ok.

if ball.is_colliding():
    var entity = ball.get_collider()
    if entity and entity.get_name() == "bat":
    #do stuff

cardoso | 2017-05-10 16:12

Thank you, that worked also, as did the answer from rredesigns. Much appreciated

Robster | 2017-05-10 22:46

:bust_in_silhouette: Reply From: rredesigns

Easy to fix. Basically, a single if can spot if entity is empty.

var entity = ball.get_collider()
if entity: # or "if entity != Nil:"
    if entity.get_name() == "bat":
    #do stuff
else:
    pass

Thank you, that was super simple. Can’t believe I didn’t think of it.

Robster | 2017-05-10 22:46