0
\$\begingroup\$

This question already has an answer here:

I am creating a random object spawning script in Unity with c#, and am wondering what the ideal way to do this task would be. So I have a list of 31 objects or so, of my special class type. Each one has an arbitrary number assigned as it's weight. This number is divided by the sum of all their weights and multiplied by 100 to make their percent chance for appearing. It's at this stage where I'm stumped. How should I go about selecting them with a random number between 0 and 100? My first idea was to give each one a range and if the random number falls within it, I select that one, but that method does not sound like it would be the most elegant and would involve like 31 IF statements. What is the standard way to do this sort of random selection?

\$\endgroup\$

marked as duplicate by Philipp, DMGregory unity Jan 25 at 22:31

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • \$\begingroup\$ Does my answer here help you? gamedev.stackexchange.com/questions/166746/… \$\endgroup\$ – Almo Jan 25 at 22:00
  • \$\begingroup\$ Would this solution still work if I had to cycle between more than two events, or if my event weights were not in any particular order in the list? Also I should have called my object's frequency in my example it's weight instead, I'll edit it as such. \$\endgroup\$ – Morgan Jan 25 at 22:12
  • \$\begingroup\$ @Morgan if your weights aren't in "any particular order" (and need to be) sort them. \$\endgroup\$ – Draco18s Jan 26 at 2:01