Topic was automatically imported from the old Question2Answer platform.
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)
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
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