How to run a function multiple times

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

I am trying to make an asteroids game and I want 3 smaller asteroids to spawn in when a bigger one is destroyed, however only one asteroid is spawned in. I am still learning gdscript so I understand if I am over looking some thing obvious, here is my code:

func _death():

parent.asteroid_count -= 1

func _Spawn():

for i in range(3):

var pos_x = rng.randf_range(-10.0,10.0)
var pos_y = rng.randf_range(-10.0,10.0)
pos = Vector2(pos_x, pos_y) + self.global_position
spawn_instance.global_position = pos

:bust_in_silhouette: Reply From: klaas

what is spawninstance where does it come from?

To spawn multiply instances you have to do something like this

it depends on what you asteroid is … a scene or a script

var spawn_scene = load("res://my_asteroid.tscn")
var script_class = load("res://")

for i in range(3):
    var posx = rng.randfrange(-10.0,10.0)
    var posy = rng.randfrange(-10.0,10.0)
    pos = Vector2(posx, posy) + self.global_position

    # here the new instance gets created
    var spawn_instance = spawn_scene .instance() #instance when its a scene
    var spawn_instance = script_class .new() # or with new when its a script

    spawn_instance.global_position = pos

Sorry, I only showed the two functions that I thought were relevant, there was more above it in the code.

Anyway, the spawn_instance variable was in the list of variables at the top of the code, moving into the _spawn function was enough to make it work. Thank you very much.

DJ_Fail87 | 2020-08-28 13:15