+1 vote

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:

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

in Engine by (17 points)
edited by

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

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

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.

1 Answer

+1 vote

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

They talk about weakref(). Try using that.

by (272 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.