How to Delay A Randomizer

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

I’m using a randomizer to spawn enemies, but it generates numbers quickly pouring out enemies. I tried using a timer but all it did was make it generate the same number every time. I’m wondering if there is anyway to delay the randomizer

here is my code currently

var a = 0
var b = false
var c = false
var d = false

func _process(delta):
a = randi()%300+1
print(a)
if a == 1:
b = true

if a == 2:
	c = true

if a == 3:
	d = true

if c == true:
	d = false 

stopping all spawning at once

#The Spawing
if b == true:
var bullet2 = Bullet2.instance()
get_parent().add_child(bullet2)
bullet2.position = $Position2D.global_position

if c == true:
	var bullet2 = Bullet2.instance()
	get_parent().add_child(bullet2)
	bullet2.position = $Position2D2.global_position

if d == true:
	var bullet2 = Bullet2.instance()
	get_parent().add_child(bullet2)
	bullet2.position = $Position2D3.global_position
:bust_in_silhouette: Reply From: jgodfrey

There’s no reason that calling randi() from a timer should cause the same number to be generated each time. You will get the same series of random numbers each time you run the scene, but that’s generally not a problem. And, you can fix that by calling randomize() one time after the scene loads (say, in _ready).

For example, this (wired to a Timer's timeout event) outputs a different number with each call:

func _on_Timer_timeout():
	var val = randi() % 300
	print(val)

I don’t really understand your spawing logic though. I’m not sure why you go to the trouble of setting 3 different variables (b, c, and d) based on a random number, but then execute (a copy of) the same code for each of them.

I’m confident that your spawn code can be simplified, but you probably need to better explain what you want the spawner to do…

Thank You for helping with this. I had looked at the randomize function but was confused on how it works. Thank you for explaining this to me. The reason for my over complicated code is that I’m a new and inexperienced in programming, I guess it ends up being every over complicated and messy. Thank You!

CreekWorks | 2020-03-24 21:37