Understanding why a var referencing a node might change

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

I have a weapon scene which launches a projectile scene, but retains a reference to that instanced node, so the second time the player hits “fire”, the launched projectile explodes into smaller projectiles.

When I scale up the number of NPCs shooting these projectiles, I pretty consistently (but not always) get a strange issue where that variable in the “weapon” that points to the last_shot projectile is pointing at a different projectile node of a different scene type that shares the same base class of Projectile.

Here is the “weapon” scene code, with the variable in question being “last_shot”, and the exception being an error because the “last_shot” node does not have the “explode” method (because it has somehow changed to point at a different projectile.

extends Weapon

var energy_use = 35
var fire_delay = 0
var fire_delay_time = 0.75
var projectile_type = preload("res://Weapons/Projectiles/BlasterBeam.tscn")
var last_shot
onready var shoot_effect = $ShootAudio
onready var explode_effect = $ExplodeAudio

func _fire(delta,energy_available):
	var energy = 0
	
	if last_shot != null and is_instance_valid(last_shot) and last_shot.traveled > 30:
		last_shot.explode()
		last_shot = null
		explode_effect.play()
	else:
		if fire_delay <= 0 and energy_available >= energy_use:
			var projectile = projectile_type.instance()
			last_shot = projectile
			spawn(projectile)
			shoot_effect.play()
			fire_delay = fire_delay_time
			energy = energy_use
		else:
			fire_delay -= delta
	return energy

In terms of inheritance, i do have an inherited “spawn” method from Weapon that different weapons use to place / position / add_child the new projectile. The projectiles also inherit from a common base that extends Area.

I don’t refer to or access the “last_shot” variable anywhere outside of this script or scene.

Any help or ideas on how to debug would be greatly appreciated! If more code is needed to fully understand, please also indicate! Thanks!

:bust_in_silhouette: Reply From: jgodfrey

Sounds like you could be experiencing this?

Also, see the conversation here:

If query does not work for deleted object - Archive - Godot Forum

jgodfrey | 2020-05-15 19:18

oh awesome, thank you, this looks like exactly that.

For reference, the approach i used to resolve it was to add after spawn:

last_shot.connect("tree_exited", self, "set",["last_shot",null])

Nikolaj Baer | 2020-05-15 19:43