Select random object from a type of class

Hey Godot users!
I have a class named “Bullet”. At runtime, I need to be able to pick a bullet at random of all the bullets currently initiated.

I know I could make an array, var bullets_intied = [] and append to it on creation and pull put the object on queue_free(). But this seems like a very bad approach to me.

I would love your input

You can use the pick_random() method of an array, to get a random value from it.

Thanks for your comment, however I am trying not to use an array I have to append to and clear myself.

1 Like

I was hoping for some kind of method like this
(fake code)

var all_bullets = Bullet.get_all_godot_instances()
var random_bullet = pick_random(all_bullets)

I can`t remember how you can get every nodes of a specific class, but instead you can do this:

var all_bullets = get_tree().get_nodes_in_group("bullets")
var random_bullet = all_bullets.pick_random()

But at first, add this code in your bullet script, add_to_group("bullets") in the ready function.

1 Like

Thanks a lot, you fixed my problem! :smiley:

1 Like