Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

RPG Drop Rate, random math function?

If I were to per-say kill a mob, and I had a 20% chance of getting a uncommon item, how would I go about scripting that? I was thinking creating a random number from 1-5 and if it landed on 3 you would get the item. Is there a better more efficient and detailed way to do this? There are no videos on free models or guides or anything about random drop rates so I'm a little stuck and that's the only thing I can think of

2 answers

✓ Accepted answer

Weighted selections

So, you want to make loot tables? Too bad, I'm telling you anyway. Loot tables are simple enough - Consider a table where every key is the unique loot, and every value is the probability of it being dropped (relative to the others)

Loot = {
  Loot1 = 1;
  Loot2 = 3;
  Loot3 = 10;
  ReallyFarTooCommonLoot = 1000;
}

Then, we can generate that table into an array of values:

newLoot = {}
for k,v in next, Loot do
  for i=1, v do
    newLoot[#newLoot+1] = k
  end
end
Loot = newLoot;

And then we can randomly select an entry from that loot table array.

Drop = Loot[math.random(#Loot)]

And now you have your chosen drop, with a weighted chance of selection.

1 comment

0

I've come back to this answer 2 years later to provide a caveat: Whilst this answer is incredibly simple, it's actually terribly poorly memory optimised. That said, it should be sufficient for most people nonetheless.

This is just an idea on how you could go about doing this

So you could use a random number and have a table and based on the random number, one of the items in the table is chosen.

local items = {"common","common","common","common","uncommon","common","common",
"common","common","uncommon","rare"}

Then say whatever happens, and they are going to get the item

local items = {"common","common","common","common","uncommon","common","common",
"common","common","uncommon","rare"}
local chosen = items[math.random(1,#items)] -- gets a random one from the list
print(chosen)

Then just if the item is common then whatever, elseif it is uncommon then whatever, elseif it is rare then whatever.

local items = {"common","common","common","common","uncommon","common","common",
"common","common","uncommon","rare"}
local chosen = items[math.random(1,#items)] -- gets a random one from the list
print(chosen)
if chosen == "common" then
	--Do whatever you want
elseif chosen == "uncommon" then
	--Do whatever
elseif chosen == "rare" then
	--Do whatever
end

If I have helped answer your question, please remember to accept my answer. Otherwise feel free to comment or message me on how I could have done better to help you. :)

This discussion is preserved as it was. New answers, comments, and votes are closed.