Removing a previously spawned instance after a new one gets created

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

Hello.
What I’m trying to achieve is to have the player to launch let’s say a simple rigid body sphere with a mouse click and upon launching a new instance the previous one gets removed from the scene so that there is always a single sphere instance in the scene.
Right now I already have the launching part working, however I cannot figure out how to despawn the previously created instance from the scene, so I have them all just accumulating in the scene.
This is my current function to create and impulse launch the sphere, only need to figure out how to remove the previously created instance (obviously the “queue_free” line doesn’t really work having it in the same function, so I commented it out:

func _launchProjectile():

if Input.is_action_just_pressed("mouse1") and enableLaunching:
	var p = projectile.instance()
	rayCastPos = get_global_transform().origin
	p.global_transform.origin = Vector3(rayCastPos)
	get_tree().get_root().add_child(p)
	p.apply_central_impulse(global_transform.basis.z*-launch_power)
	#p.queue_free()
	
:bust_in_silhouette: Reply From: jgodfrey

It sounds like you just want to retain a reference to the “previous” projectile and remove it once you’ve created a new one. Something like the below should do that.

var prev_projectile = null

func _launchProjectile():

    if Input.is_action_just_pressed("mouse1") and enableLaunching:
        var p = projectile.instance()
        rayCastPos = get_global_transform().origin
        p.global_transform.origin = Vector3(rayCastPos)
        get_tree().get_root().add_child(p)
        p.apply_central_impulse(global_transform.basis.z*-launch_power)
        if prev_projectile:
            prev_projectile.queue_free()
        prev_projectile = p

That’s it! That did the trick.
Thank you very much!

Paulaza | 2022-07-18 19:34