An enemy that keeps the player in a variable and checks target != null goes on attacking a player that is dead but still on screen, and when that player is freed and a new one spawns, it holds nothing and never looks for the new one. In our Godot 4.7 test it hit the dead player twice during a 1 second death animation, then never attacked the respawned player. Ask for the target every physics frame, drop it when it is dead, freed or queued for deletion, and search the player group again: the new player was picked up on the first physics frame after it spawned.
The code
Save it as target_keeper.gd and give each enemy one: var keep = preload("res://target_keeper.gd").new(). Every physics frame, var target = keep.get_target(self), and attack or chase only when it is not null. Put your player in the player group, and give it a dead property that is true while its death animation plays.
extends RefCounted
## An enemy's target that is dropped the moment it dies, is freed or is about
## to be freed, and found again in a group when a new one appears, such as a
## player who respawns as a new node. Ask get_target(self) every physics frame
## instead of keeping the node in a variable of your own.
var group := &"player" # the group the targets are in
var max_distance := 50.0 # only pick targets this close
var node: Node3D = null # the current target, or null
func get_target(from: Node3D) -> Node3D:
if not usable(node):
node = null
var best := max_distance
for n in from.get_tree().get_nodes_in_group(group):
if n is Node3D and usable(n):
var d: float = from.global_position.distance_to(n.global_position)
if d <= best:
best = d
node = n
return node
func usable(n) -> bool: # alive, in the tree, not freed or queued for deletion
return is_instance_valid(n) and n.is_inside_tree() and not n.is_queued_for_deletion() and n.get("dead") != true
What we measured
A player that is alive for 1 second, then dead for 1 second while its body stays on screen, then freed. One second later a new player spawns. Three enemies attack every 0.5 seconds whenever they have a target. Two runs gave the same numbers.
- Target in a variable,
if target != null: hits at 0.02, 0.53, 1.05 and 1.57 seconds. The last two landed on the dead player. After it was freed: no hits, no errors, and none on the new player. - Target in a variable,
if is_instance_valid(target): exactly the same hits. - The script: hits at 0.02 and 0.53, none while the player was dead, then the new player at 2.98 and 3.50. It picked up the new player at 2.98, the first physics frame after it spawned.
- Right after
queue_free(), in the same frame:is_instance_valid()true and!= nulltrue, whileis_queued_for_deletion()was already true. Once it was freed:is_instance_valid()false,== nulltrue, and printing it gave <Freed Object>.
Why it happens
A variable holds the node it was given and nothing else. It does not know the player died, because dying is your game's idea, not Godot's, and it does not know a new player exists, because the new player is a different node. Once the old node is freed, Godot 4.7 makes the variable compare equal to null, so the check stops the attacks without an error, but the enemy just stands there. There is also a gap: between queue_free() and the end of the frame the node still passes both checks, so code that runs in that frame can hit a player that is about to disappear.
What to change
group: the group to search, for example"player"or"ally"for a healer that follows whoever is alive.max_distance: enemies only pick a new target this close, so the whole map does not run to the respawn point.- A player who should not be hit for a moment after coming back: give it a short time with dead still true, or a separate flag your attack code checks.
- Turning to face the target: the short way around.
The moment the player comes back: Holy & Light VFX for Godot 4 has a Resurrection Pillar, Heal Circle, Halo and Light Wings, and a showcase scene built around a resurrection. Play the pillar where the new player spawns, and the enemies find them the next physics frame.
Tested in Godot 4.7 with the Compatibility renderer.
Ready-made: Holy & Light VFX for Godot 4 has a Resurrection Pillar, heal circles, halos and smite beams, and a showcase scene built around a resurrection.
More how-tos for Holy & Light VFX for Godot 4: A glowing circle on the ground · A force field shield with a hit ripple
More how-tos: Game systems
- Hover a 3D object inside a SubViewport
- A turned building that covers the cells it stands on
- An inventory that never loses an item and never overfills a stack
- A JSON save that loads back exactly what you saved
- Fire that spreads one cell per step, in every direction
- A pooled enemy that comes back as fresh as a new one
- Poison, burn and bleed that keep ticking when applied again
- XP, qi and gold that keep growing without going negative
- Count slot line wins with wilds in front
- Random directions spread evenly over a sphere or a cone
- Count a lap only when the car really went round
- Make a seed repeat: daily runs, replays and roguelike seeds
- Offline progress that counts the time the game was closed
- A chance roll without the long bad-luck streaks
- Check crafting recipes in any order, with the right counts
- Make HP and mana regen the same at any frame rate
- Damage over time with the right number of ticks
- Spawn enemies where the camera cannot see them
- Keep a chasing horde from stacking into one enemy
- Make the fish bite after the same wait at any frame rate
- Snap buildings to the right grid cell on both sides of the origin
- Make a cooking timer fire once, on time
- Pick from a weighted loot table with the right chances
- Level up as many times as the XP covers
- Walk a patrol guard to each point without overshooting
- Remove items from an Array while checking them, without skipping any
- Scatter spikes, roots or trees in a circle without overlaps
- Count and take crafting items from every stack
- Play random sounds and events without obvious repeats
- Pick the growth image so the ripe one shows exactly when the crop can be picked
- Turn a day counter into season, day and year without a day 0
- An enemy that dies once, however many hits land
- A fair shuffle you can replay
- A ghost that drives the lap at real speed
- A vision cone that does not flicker at the edge
- Move a group of units without a pile-up
- A sprinkler that waters a round patch
- A slot reel that always lands forward on the result
- A crowd of NPCs that never emote or bob in step
- A song position that moves on every frame
- Nodes your editor tool adds that stay in the scene