My program crashes for trying to access the attribute of a null object, even though i checked before to made sure it wasnt NULL

Viewed 63

i am currently trying to make a tower defense in godot.

Each one of my towers have a variable pointing to the enemy they're currently targeting. This is used to, for example, animate their bows towards the enemies.

However, when the target dies, and is freed from the scene tree, it causes the game to crash for trying to access its attributes, EVEN THOUGH i null-checked it just before

Here are the problematic lines :


    if not target == null:
        $BowAnchor.look_at(target.global_position)

1 Answers

When an object is removed, the variables that point to it do not become null automatically. Instead they will be pointing to a freed object.

To address that use is_instance_valid:

if is_instance_valid(target):
    pass

Using is_instance_valid you are checking for null, and also for a reference to a freed object.

Other similar checks you might be interested in are is_queued_for_deletion of the Object class, and is_inside_tree of the Node class.

Related