"Previously freed instance" crashes my game

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

if target != null && target.is_in_group(“player”)

I’m using this to avoid “target.is_in_group()” crashing the game when there is no target. But a “previously freed instance” apprently passes “!= null”. I fixed this earlier by instead using “target is Node2D”, but lo and behold in godot 3.2 that now also causes a crash:
“Left operand of “is” was already freed”

How do I avoid this causing a crash?

:bust_in_silhouette: Reply From: Magso

When ever player is freed use remove_child(player) instead. The error is happening because even though you’re using and in the if statement target.is_in_group("player") is still being checked so it would be better to make it two if statements.

if target:
    if target.is_in_group("player"):
        ...

Based on the testing I’ve done conditions with && between get checked from left to right and it stops if it runs into a false condition, so this won’t make a difference. The problem is that a previously freed instance passes the first check.

Not sure how it relates to the rest of the comment, but I guess I’ll try using get_parent().remove_child(self) instead of queue_free(), to see if that makes a difference.

MOSN | 2020-01-30 13:01

Seems like that might actually have worked, so thanks :slight_smile:
Still would like to know a failsafe way to check that a variable is a currently existing node though. Seems weird to me that a “previously freed instance” returns true from “if target:”, but with that being the case is there another condition you could use to make sure target is neither null or a previously freed instance?

MOSN | 2020-01-30 13:57

Not really, queue_free() should cause the reference to be lost so the variable should return null. In fact I’m sure that’s why it’s better to use queue_free() rather than free().

Magso | 2020-01-30 15:09

Well… But that just doesn’t seem to be the case.
But at least it’s working with the new method.

MOSN | 2020-01-30 17:44

:bust_in_silhouette: Reply From: Merlin1846

From what I can tell the whole problem is here

  if target != null && target.isingroup("player")

should be

  if target != null && target.is_in_group("player")

then it should work

That’s what I’m already using but two of _ turns into italic text when i post for some reason.

MOSN | 2020-01-30 12:53

When the code isn’t formated correctly underscores cause italics even though the italics option uses *

Magso | 2020-01-30 13:55

:bust_in_silhouette: Reply From: Pineappletooth

A bit late but for anyone that has the same problem, since 3.x now you just have to use is_instance_valid(target)

if is_instance_valid(target):
    ...

https://docs.godotengine.org/es/stable/classes/class_@gdscript.html#class-gdscript-method-is-instance-valid