How should I code something in my game to have a random chance to drop a single item?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By MercyFalls
var random = RandomNumberGenerator.new()

func _ready():
random.randomize()
var n = random.randi_range(1, 100)

How would I code for it to check the randomly generated value and decide whether to drop the item or not based on a drop chance? Sorry I’m very new to all of this and just trying my best to learn as I go. I have checked out a bunch of resources I could find on using RNG + Arrays in Godot but I’m not quite sure how to code it out for myself. Also, I figured using an array might be redundant since I will only have 1 item on my drop table? But perhaps if I wanted to add more items later down the line it would be useful to just use arrays anyway. Any advice appreciated.

:bust_in_silhouette: Reply From: sash-rc

For a simple case, use

func _ready():
  randomize()

var probability : int = 10 # 1/10 chance
if (randi() % probability) == (probability - 1): 
  it_happened() # do something 

For a multiple items (Array) I suggest you need two answers: whether you want to drop something at all (use example above) and if it happens, check which one

var items = ["First", "Second", "Third"] # your items

# first check if items exist, actually should be done before first query
if items.size() > 0 : 
  var idx : int = randi() % items.size() # item index
  var item = items[idx] # do something with item
  items.remove(idx) # at least remove it from array