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):
- Raycast around your turret to find possible target enemies.
- 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.