Attempt to call function 'get transform' in base 'previously freed instance' on a null instance

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

Im making a tower defense game and it has torrents in them. I’ve made the code so that the torrents look at passing enemies and shoot them. I’ve been stuck on this for 2 WEEKS now when the torrents shoot the enemies and they are freed it crashes.

The main code that keeps messing up is :

var target_ enemy = global.enemy.get_ global_ transform().origin-get_ global_transform().origin;

Is there a work around since the variable keeps getting freed? Is there a better code for tracking the enemy?

I’ve tried adding

If target_enemy == null:
Return;

And that’s not working either! Yes I am a noob someone please help me :frowning:

How are you freeing the enmies, are you using queue_free()?

quijipixel | 2018-02-04 17:39

Yes I am. Is there a better way to do this? And thank you so much for replying!

Anicsim | 2018-02-04 19:19

I’m not sure as I don’t know how are you handling your enemy code, but it looks as if you are getting the enemy position from a global object.The error is triggering in the global.enemy part of that line not on the target_enemy variable.

I think that a better approach is to let the turret attack every enemy that’s close to his position without the turret knowing who he is. This could be an basic algorithm for the turret’s _physics_process (or _fixed_process if you are on Godot 2):

  1. Raycast around your turret to find possible target enemies.
  2. If enemies were found, cycle through them and shoot them.
    That’s about it.

The enemies should be an independent scene that will handle it’s own collision with the bullet as well as free himself when dead, that way when the turret seeks targets again, if the enemy is freed it won’t attempt to shoot it.

You can use the Physics2DDirectSpaceState to cast a Circle shape (instead of a ray) to facilitate the search for enemies.

quijipixel | 2018-02-05 11:32

:bust_in_silhouette: Reply From: lavaduder

This question has been answered here: https://forum.godotengine.org/3645/previously-freed-instance-error?show=3645#q3645

They talk about weakref(). Try using that.