renetc
November 21, 2024, 8:12am
1
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
KingGD
November 21, 2024, 8:14am
2
You can use the pick_random()
method of an array, to get a random value from it.
renetc
November 21, 2024, 8:17am
3
Thanks for your comment, however I am trying not to use an array I have to append to and clear myself.
1 Like
renetc
November 21, 2024, 8:18am
4
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)
KingGD
November 21, 2024, 8:24am
5
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
renetc
November 21, 2024, 9:06am
6
KingGD:
get_nodes_in_group
Thanks a lot, you fixed my problem!
1 Like