How to Create a RANDOM LOOT TABLE in Unity C#

  Рет қаралды 63,059

gamedev:hq

gamedev:hq

Күн бұрын

Пікірлер: 96
@gamedevhq
@gamedevhq 9 күн бұрын
🚀 Launch Your Tech Career - *FREE Training:* gamedevhq.com/free
@ethanffischer
@ethanffischer 4 жыл бұрын
It took me a little while to understand why this works. The numbers in table aren't percentages, they're distributions. So for example, say you set up table like { 2, 2, 4} which corresponded with items { sword, shield, bomb}. You're essentially putting these items in a hat and drawing a random one from it. The hat's contents would look like this sword sword shield shield bomb bomb bomb bomb Hope this helps someone!
@gamedevhq
@gamedevhq 4 жыл бұрын
Shit, that helps me lol -- Well done!
@fuzzy-02
@fuzzy-02 2 жыл бұрын
bro i literraly understood nothing of how the code worked until I read this comment and got reminded of my probability classes back in school.
@Fire-Pixel
@Fire-Pixel 2 жыл бұрын
Dont think to complicated. The total number divided by the number for an item is the chance for that item. If the total number is 200 and the number for the item is 50, then the chance for that item is 25% (200/50 = 4( into percentages is 100/4 = 25%))
@Mayur7Garg
@Mayur7Garg 5 жыл бұрын
We can also use cumulative frequencies instead of absolute frequencies. So instead of using 60, 30, 10, we could use values 60, 90, 100. The advantage here is that we need not be worried about the rarest being at the last. Items can be in any order of rarity which makes it easier to add items in the future to the end of the list. That is if I wanted a 4th item with a rarity of 30, I could simply add a 4th value of 130 to the table. The total would be the last item of the array. We then generate a random number similarly and then check if the number is smaller than the first value in the table. If it is, item is the first one else we check with the second one (without subtracting anything) and so on.
@gamedevhq
@gamedevhq 5 жыл бұрын
Correct! Way to go :)
@scorpion666lair
@scorpion666lair 5 жыл бұрын
I think this is a much better solution, take the scenario where you have a stack of items being 30, 32, 60. The chances of hitting the middle item becomes the rarest. Thanks for your input Mayur!
@genzuo
@genzuo 5 жыл бұрын
that's a really great way of doing it, really flexible, thanks for sharing
@Quoteory
@Quoteory 4 жыл бұрын
@@scorpion666lair This doesn't seem to be the case, I generated 1 million Items and the 32 weight item count is slightly higher than 30 and 60 is highest did it with a lot more items and weights and the same results
@bruhvioli
@bruhvioli 4 жыл бұрын
thanks man this helped me a lot. and i think it's working but just to be sure it would look like this right? if (randomNumber
@yale3d
@yale3d 4 жыл бұрын
2:25 Actually, yes, you can do that, and you *don't need* to put rarest at the bottom. It won't make any difference. It doesn't matter if your "rare" item is from 0-2 or 147-149 - it just weights 3 anyways. It's like "you have 5% - pick a number and roll D20 a thousand times!" Your succes rate will be around 5% overall, no matter what is the number of your choice. Other than that, good one.
@Fire-Pixel
@Fire-Pixel 2 жыл бұрын
Youre right, it took me a while to figure it out but you are right. This means you can just put any numbers in the thing. 50, 20, 40, 50, 20, 10, 100, 40. It doesnt change a thing :) The only thing thag counts is: The lower the number, the lower the chance....
@GeorgeZaharia
@GeorgeZaharia 4 жыл бұрын
i avoided so long C++ and C# and now i see they are actually easier to work with than javascript ... which is insane and amazing.
@ericf.2267
@ericf.2267 5 жыл бұрын
Thanks for great info Jon! Just a quick clarification (correct me if I'm wrong), I believe the second parameter used in Random.Range() is exclusive when using integers. So in the example code the variable "total" will never be selected as a random integer. So if you only had two weights of 9 and 1, I don't think the code could ever randomly select the item with the weight of 1.
@gamedevhq
@gamedevhq 5 жыл бұрын
Thanks for pointing this out!! Correct. It would need to be random range between 0 and Total + 1.
@manzell
@manzell 2 жыл бұрын
@@gamedevhq This is incorrect. If your weights are 1 and 9; your total will be 10. Random.Range(0, total) will return a number between 0f and 9.99999f - if you do Total+1 you'll periodically get index-out-of-range errors.
@AndreiDante
@AndreiDante 2 жыл бұрын
Couldn't find a better explanation for the random loot table!!
@gamedevhq
@gamedevhq 5 жыл бұрын
Join us for our quarterly Game Jam! March 8-10th : kzbin.info/www/bejne/ZnKQlIyvYq6rh7M
@rmt3589
@rmt3589 2 жыл бұрын
Do y'all still do quarterly game jams?
@brunogutierrezchavez1989
@brunogutierrezchavez1989 4 жыл бұрын
Nice algorithm! Actually the algorithm works with the weights disorderer 'cause you are basically setting an interval for each weight and with the process you make, it simply checks in what interval the random number is, first you check the first interval, then the second and so on! Also I think is good to ordered 'cause with a bunch of code you may have problems and isn't obvious that it will work
@TopBagon
@TopBagon 5 жыл бұрын
Thanks a lot for the amazing lesson. One of the best explanations I've ever heard for sure. I thought it'd be difficult but thanks to your amazing explanation I get it all
@petelovagssecondaccount5291
@petelovagssecondaccount5291 4 жыл бұрын
You are an absolute legend
@Glori4n
@Glori4n 2 жыл бұрын
Pretty solid explanations, thank you for that!
@infinitefretboard
@infinitefretboard 5 жыл бұрын
Thanks for the vid! This sets me in the right direction. One idea is to make a list of structs instead of having two different lists. The struct would contain two members: an item and a drop weight. That way you don't have to manage 2 different lists and worry that an item has the wrong drop weight associated with it.
@aussieraver7182
@aussieraver7182 2 жыл бұрын
Thanks for the tutorial!
@manzell
@manzell 2 жыл бұрын
10:00 if you subtract your weight from your random value first, you can check if your random value is
@prashantkhandelwal755
@prashantkhandelwal755 4 жыл бұрын
i had bought your 2 courses from udemy. and i learnt alot from them. thank you sir. 🙌🙌
@thomasreed2883
@thomasreed2883 5 жыл бұрын
Thanks so much for clarifying this I've been beating my head against a wall for an hour now trying to understand probability in unity it for my game's enchanting system.
@Fire-Pixel
@Fire-Pixel 2 жыл бұрын
Dont think to complicated. The total number divided by the number for an item is the chance for that item. If the total number is 200 and the number for the item is 50, then the chance for that item is 25% (200/50 = 4( into percentages is 100/4 = 25%))
@JulianSpoon
@JulianSpoon 4 жыл бұрын
Thanks, this helped me a lot.
@rafiiiiii
@rafiiiiii 4 жыл бұрын
Great explanation !
@hierayku873
@hierayku873 5 жыл бұрын
Thank you, it's really useful!
@bruhvioli
@bruhvioli 4 жыл бұрын
Cool breakdown! Just to let you know, in the video you say you would run the script on press of the space bar but you never add that part to the script. Also, it isn't super obvious how you could perform different functions in the script depending on the random number generated. That would have been a nice bonus.
@dolphin-sd
@dolphin-sd 3 жыл бұрын
thanks, really helped me out there!
@CottidaeSEA
@CottidaeSEA 4 жыл бұрын
I don't know if I'm missing something, but you should be able to simplify the code by subtracting the weight first, then checking if randomNumber
@TheEnde124
@TheEnde124 5 жыл бұрын
Nice, very helpful!
@jessicaoreilly9260
@jessicaoreilly9260 5 жыл бұрын
Thank you, Awesome lesson.
@gamedevhq
@gamedevhq 5 жыл бұрын
Thanks, Jessica!
@biaggiopietro9739
@biaggiopietro9739 2 жыл бұрын
hi thanx for video.How to make music?i like 🙂
@xerodeus2337
@xerodeus2337 3 жыл бұрын
hmmm how would this work for like 1000 items in the game? having to assign a number for each item that isn't the same as every other item, not sure that would work too well. I think you'd have to create two tables, one for the rarity of the item that drops, and then, depending on the rarity you get, it goes through another table containing only rare items, and pulls a random item from that table. Also, I'm not quite sure why you would work through the table backwards, subtracting each time. Why not just say, roll a 32, then check to see if 32 is
@invalidusername9490
@invalidusername9490 2 жыл бұрын
Actually i wanna know about what you said at the end too.....that should work fine...But is there any reason for not using this?
@phambaoha170
@phambaoha170 5 жыл бұрын
Thank you.
@gamedevhq
@gamedevhq 5 жыл бұрын
Of course!
@miskotakelis3092
@miskotakelis3092 Жыл бұрын
if there are multiple items of the same rarity, would it still work?
@user-gy6cv3ug5i
@user-gy6cv3ug5i 4 жыл бұрын
Would it work the same way if each sword had a weight variable and you looped over each sword, got the sum of the weights then got a random number between 0 and the sum of the weights, then looped over all swords again and checked if the weight is greater than the random number and if not increment a new sum, repeating this loop until the new sum is greater than the random index, picking that number? No need for it to add up to a clean 100 or 1000 in this case as far as I can see
@TheGamingWiccan
@TheGamingWiccan 5 жыл бұрын
how would i go about integrating this into an inventory system?
@JtagSheep
@JtagSheep 5 жыл бұрын
build systems that integrate, have an item system that is re usable by many things, inventory, loot spawn, stores etc, you wanna try and make your stuff as decoupled as possible so that it takes care of itself and can be easy interacted with and used etc. Instead of your items and item system containing of the colliders/tirggers rely on your loot system to do that, when you drop an item into the world the loot system is responsible for processing that, the same as when it spawns a new item for pickup by players it is responsible for that. This way each system takes care of its own thing but the items can be re used easily, all an item should be is its model with its basic animator attached if you require animations on the model and something on the model to hold its data maybe its rigidbody etc, the item is just a 3d model prefab with the basic data/references script that other systems can use, this allows much more flexibility into changing models and even re factoring code. Decoupling is your friend I learnt this from many popular web dev frameworks ! :)
@IvisibleCat
@IvisibleCat 5 жыл бұрын
Thank you ! please keep doing Videos like this. Also starting your new Unity Survival Course on Udemy :)
@gamedevhq
@gamedevhq 5 жыл бұрын
Awesome, IvisibleCat! Thanks for watching! new videos every week :)
@paufenollosa
@paufenollosa 3 жыл бұрын
The values on the table must be in descendent order to work fine. Edit: Totally false what I said. It works perfectly in any order!
@nixsnake
@nixsnake 5 жыл бұрын
Hello, are u planning some series about Ureal Engine 4 Game Dev?
@gamedevhq
@gamedevhq 5 жыл бұрын
Hey mate, At the current moment, due to our partnership we are 100% focused on Unity!
@457Deniz457
@457Deniz457 5 жыл бұрын
@@gamedevhq Glad to hear that :)
@MasterGouz
@MasterGouz 4 жыл бұрын
Very useful tutorial! How could I make it work if my loot probabilities are variables and not constant numbers?
@Dippps
@Dippps 4 жыл бұрын
In my game I have a chance for each item and foreach get random number if it is in range then drop. do while loot table is equal to guaranteed amount of items.
@Stonegoal
@Stonegoal 4 жыл бұрын
Amazing idea specialize types of loot per monster/boss to promote variety in farming for different builds plus it would give reasons for why that loot drops from that monster/boss. I guess it is good you are helping people code. The main problem is content and story, there are so many games coming out I can't keep up but most are grind fest and weak stories. Classic WOW I wanted gear we would farm set bosses until we got the stuff we wanted. Complete randomness(most common ARPGs) and tokens(common WOW) has cheapened farming.
@Hemsk
@Hemsk 3 жыл бұрын
@GameDevHQ I followed this tutorial, and it works fine until the subtraction is supposed to take place, where my script just stops working and ends up returning 1 or 2 as randomNumber everytime. Do you know what went wrong? The only difference I can see is that I have changed the var "item"'s name to "creature". My script: public class CreatureTable : MonoBehaviour { public int[] table = { 50, //Creature 1 40, //Creature 2 30, 20, 10, 6, 3, 1 }; public int total; public int randomNumber; void Start() { foreach (var creature in table) { total += creature; } randomNumber = Random.Range(0, total); //WORKS FINE UNTIL HERE foreach (var weight in table) //THIS IS WHERE IT BREAKS { if (randomNumber
@tobihudiat
@tobihudiat 3 жыл бұрын
Save, close Unity, Start Unity.
@fernandochaparro2788
@fernandochaparro2788 3 жыл бұрын
Use break if the statement Is true
@Hemsk
@Hemsk 3 жыл бұрын
@@fernandochaparro2788 I ended up using a different system all together. Thanks for trying to help though!
@ryanmoulla2409
@ryanmoulla2409 5 жыл бұрын
Thanks a lot for this video but how can I make that when it is element 0, coins spawn and if it is element 1, nothing happen?
@tonytran07
@tonytran07 2 жыл бұрын
I see only one problem. It'll always calculate a Subtraction on each call, which is inefficient. Why not just get the sum of weight at start() and run a comparison instead? 60, 30, 10 => 60, 90, 100
@yahoruz
@yahoruz 4 жыл бұрын
oh this is dope :O
@Euginium
@Euginium 4 жыл бұрын
so how does the Ratio work? if sword A and sword B is 600 does it mean that both has 50% chance of getting either one?
@frozenphoenixstudio
@frozenphoenixstudio 4 жыл бұрын
Assuming we are still using all 3 swords and your weights are (A=600, B=600, C=100) then you'd have a 46%(ish) of getting either sword a or b and 8%(ish) for sword c (rounded values). You can tell the percentage of getting each item by getting the weight of your item and dividing it by the total weight and multiplying this amount by 100. E.g sword a = 600 so 600 divided by the total weight (600+600+100 = 1300) which equals 0.46. Multiply this by 100 and you get 46.
@TheNamesJT
@TheNamesJT 5 жыл бұрын
could you show me how to make a loot table with values? like instead of swords being what the player would get it. The player would get a value? aka click this and receive a gold bonus of value, value,value,value which has weights too.
@Husmanmusic
@Husmanmusic 4 жыл бұрын
Awesome video! How would I go about instantiating this script from when a enemy dies? so that it spawns the item based on this system?
@GolfBusters
@GolfBusters 4 жыл бұрын
I think you could do it by making an OnDisable() function and instantiating the prefab when the item becomes disabled.
@CorpSlay
@CorpSlay 3 жыл бұрын
I think you could do this creating a gameobject with this script inside.. Then in the health script from the enemy create a public GameObject box; then when if ( health -= 0) use the instantiate method, and then destroy (gameObject);. And put the gameobject with the random loot script in the slot (box). Is really easy
@meedogames4916
@meedogames4916 4 жыл бұрын
Hello, thank you for explaining that it is easy now, but if the enemy is dead and I want to drop gold or things, how do I do it, thank you again
@sebnorsan
@sebnorsan 3 жыл бұрын
There was a bug in my code where the award would be given to me multiple times instead of just breaking out of the foreach loop when I started the game. If anyone else has that bug you just need to write foreach (var weight in table) { if (randomNumber
@fdsasdfahzxcc
@fdsasdfahzxcc 3 жыл бұрын
I recognize you from your voice, I made your unity course
@DaMatrixxMann
@DaMatrixxMann 4 жыл бұрын
Hey there. I tried following your code here and did everything exactly like you did except for instead of a light, I am calling to instantiate a weapon. I created the GameObjects list and added each potential weapon in the same order as my table (in terms of rarity), and call to Instantiate(weapon[i]) at a spawnPoint that I set up, but it comes back with a NullReference error - object not set to an instance of an object and the error is at the line where I instantiate the item. Am I doing something wrong here? for(int i = 0; i < table.Length; i++) { if(randomNumber
@fuzzy-02
@fuzzy-02 2 жыл бұрын
So basically : if he got 60A- 30B- 10C and he rolled and got a 61 why does he get B? because imagine him having a list, items 1 to 60 just being As then items 61 to 90 being Bs and 91 to 100 being Cs, so when he got 61 he read thru the list and item 61 is a B. this is way better than percentages, because you can just make A, B or C not an item but rather another set of drop tables and roll other stuff.
@Fire-Pixel
@Fire-Pixel 2 жыл бұрын
It works really well yes. And you can actually just use any kind of numbers you like. 10, 20, 60, 40, 30, 20, 10. The order doesnt matter. The lower the number, the lower the chance
@glenzhang3646
@glenzhang3646 5 жыл бұрын
If you have 2 items in the array with the same drop chance like in the end of the video, won't you only get the prior one in the array?
@pepperdayjackpac4521
@pepperdayjackpac4521 2 жыл бұрын
no, because rand will be different each time. Let's say you have {A = 50, B = 50} as 2 items with the same weights. If rand is 89, it will not be A because 100 > 50, so 50 will be subtracted from rand. Then on the next iteration, we move on to the next item which is B. Rand, which is now 39, is compared to the weight of B. 39 < 50, so you'll get item B. If rand is 32, then you get item A bc 32 < 50 I hope that clears it up
@bloodartist5235
@bloodartist5235 4 ай бұрын
i think you have a little misstake there, you make Random.Range(0, total) who make a number, in this case, bettween 0 and 99 So yeah you have a total a 100 number but you have 61 number who are true to
@TheXdestruidor
@TheXdestruidor 3 жыл бұрын
if I have 2 items with the same probability, how i can make this works?
@Fire-Pixel
@Fire-Pixel 2 жыл бұрын
If you have 10 ,10 A result of 5 would select a, and a result higher then 10 would select B =11 is b
@denisedelbroek6320
@denisedelbroek6320 5 жыл бұрын
Does it work the same with more then 3?
@gamedevhq
@gamedevhq 5 жыл бұрын
Give it a shot ;)
@Stonegoal
@Stonegoal 4 жыл бұрын
I have only done a slight amount of coding in high school but those 3 items could have been place holders for common, rare and epic at which time you do another roll figuring out what type of item that is. Think about how randomized Diablo 3's items were they were forced to tailor item drop and item creation(when dropped) on the class currently playing.
@pederslothzuricho7685
@pederslothzuricho7685 4 жыл бұрын
In my experience these loot tables are faulty, because the random numbers are not really that random. I believe a better way to do it is a more controlled distribution. So Gaussian Normalized Random numbers: By making the 3 sigma rule apply, you can specify rarities, and depending on the range, you can dynamically program loot tables to be actual table entries. And by looking at this table you can immediately see which entries are most probable, without a crazy RNG range. If one is smart, you can even apply the generator from each loot table, and then add elements with rarity tier or more specific, and specify which table to add it to, or remove from. You can just add 1 line more if you need to add it to more than 1 table, or move the element to a different table. Without affecting the drop chance for the other elements in the table relative to the remaining elements. This is all theoretical, but i intend to try it out in a patch to a prototype during the spring. See this, if you're confused: answers.unity.com/questions/421968/normal-distribution-random.html Theoretically you can add modifiers to boost the dropchance of an element temporarily too. Its worth trying if you find the drop chances are in consistent with a basic implementation.
@baltusd
@baltusd 4 жыл бұрын
i want tis
@AboA7ma11
@AboA7ma11 4 жыл бұрын
Thank you for this amazing video, but ill stick to my code although your code is much more efficient than mine but, mine is easier to understand in my opinion here it is if anyone wants it public class testingprobabilities : MonoBehaviour { public int Randomizednumber, total = 100,Probability1,Probability2,Probability3; void Start() { //Probabilities Value Probability3 = 10; Probabiltiy2 = 20; Probabiltiy1 = 70; // Random Integer's Value Randomizednumber = (Random.Range(0, total)); //if our random integer is less than or equals to probabilty1 if (Randomizednumber
@guardiangames6925
@guardiangames6925 5 жыл бұрын
While this tutorial is useful its really hard to follow with how fast you go
@dman-tm
@dman-tm 3 жыл бұрын
this math in the vidfeo is so wrong. i don't even know how to write a single line of code and i know this isn't write. sword C has a greater chance than 10 percent. like alot more like roughly 20 % chance. i don't liek this video unless someone can prove me wrong
@jimzkie5634
@jimzkie5634 3 жыл бұрын
Is this how RNG works on XCOM and Darkest Dungeon?
@gamedevhq
@gamedevhq 3 жыл бұрын
Possibly - It's quite popular. This is how its primary done with the casino industries. But I believe runescape did a similar weighted loot table.
I Made the Same Game in 8 Engines
12:34
Emeral
Рет қаралды 4,3 МЛН
Be CAREFUL with Scriptable Objects!
8:27
Code Monkey
Рет қаралды 86 М.
Don’t Choose The Wrong Box 😱
00:41
Topper Guild
Рет қаралды 62 МЛН
Гениальное изобретение из обычного стаканчика!
00:31
Лютая физика | Олимпиадная физика
Рет қаралды 4,8 МЛН
Арыстанның айқасы, Тәуіржанның шайқасы!
25:51
QosLike / ҚосЛайк / Косылайық
Рет қаралды 700 М.
Flexible LOOT SYSTEM in Unity with Random Drop Rates
13:24
Why I am NOT Making These Enemies
17:06
Deynum Studio
Рет қаралды 216 М.
I Coded a Nuclear Physics Simulator to Play God in VR
44:21
Thomas Wald
Рет қаралды 122 М.
20 Advanced Coding Tips For Big Unity Projects
22:23
Tesseract
Рет қаралды 209 М.
Unity3D Mistakes I made that you should avoid
17:32
Jason Weimann (GameDev)
Рет қаралды 338 М.
choosing a game engine is easy, actually
15:08
samyam
Рет қаралды 661 М.
every step to actually make your dream game (then sell it)
24:27
RANDOM LOOT Table in Unity - GACHA System
7:24
Dev Leonardo
Рет қаралды 10 М.
Drop Loot Auto Flyback to Player with Unity
6:10
Indie Nuggets
Рет қаралды 20 М.
20 Unity Tips in 10 MINUTES!
10:57
Code Monkey
Рет қаралды 59 М.
Don’t Choose The Wrong Box 😱
00:41
Topper Guild
Рет қаралды 62 МЛН