0 votes

first i creating instance

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

then i adding it as a child

func spawnenemy():

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 = load("Enemy.tscn").instance()

am i doing it right?

Godot version v3.4.4
in Engine by (24 points)

1 Answer

+1 vote

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()

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 (19,270 points)

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()

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:

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

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()

It works, thanks

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.