is this a correct way to add and remove enemy instance from a scene?

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

first i creating instance

onready var enemy = load("Enemy.tscn").instance()

then i adding it as a child

func spawnenemy():
	add_child(enemy)

then i removing it (if hp = 0) with the this line of code and immediately creating new instance again in case i want to spawn new enemy with add_child(enemy)

func removeenemy():
    enemy.queue_free()
    enemy = load("Enemy.tscn").instance()

am i doing it right?

:bust_in_silhouette: Reply From: jgodfrey

That should work, but the sample below is probably more standard and efficient.

onready var enemy_scene = load("Enemy.tscn")
var enemy

func spawnenemy():
    enemy = add_child(enemy_scene.instance())

func removeenemy()
    enemy.queue_free()
    spawnenemy()

The main differences are:

  • Use of preload instead of load (and do it only once)
  • Don’t create an instance at preload / load time
  • Create a new instance of the preloaded scene in your spawnenemy function
  • After removing a deceased enemy, just call spawnenemy again. There’s no reason to repeat the same code again…

by doing this method i getting an error when i trying to remove enemy: Invalid call. Nonexistent function ‘queue_free’ in base ‘Nil’. on line enemy.queue_free()

hrp | 2022-08-22 12:04

A few things to notice…

  • The onready var is named enemy_scene
  • enemy is created as a script-global variable
  • enemy is assigned in spawnenemy()
  • enemy is queue_free()'d in removeenemy()

Do you have all that right in your script? Also, you can’t call removeenemy() before you’ve called spawnenemy().

You could add this to make it a bit safer…

func removeenemy()
    if enemy:
        enemy.queue_free()
    spawnenemy()

jgodfrey | 2022-08-22 13:07

yes, everything is right here is screen
enter image description here
when i printing enemy’s var, output console saying its null but enemy is spawned and i can create as many instances as i want but cant call the var

hrp | 2022-08-22 13:23

Ah, yes. Sorry, this is my fault. This code:

func spawnenemy():
    enemy = add_child(enemy_scene.instance())

needs to be…

func spawnenemy():
    enemy = enemy_scene.instance()
    add_child(enemy)

jgodfrey | 2022-08-22 13:33

It works, thanks

hrp | 2022-08-22 13:36