• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
Question by SuperRaed · Apr 14, 2016 at 09:24 AM · randomplayerprefsrandom.range

how to randomly instantiate prefabs but each with it's own probability?

I'm building a space shooter game and throughout the game I want to randomly instantiate 10 items but each with it's own probability, such that items with the most significance will show up the least and those with least impact would show up the most. so far I'm t$$anonymous$$nking about using Random.Range(0,101); and using if statements in such a way: 0-10 item 1 =10% probability 10-20 item2=10% 20-25 item3 =5%

is t$$anonymous$$s a good way? or is there a better way ?

Comment

People who like this

0 Show 0
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image

Answer by noppander · Oct 12, 2016 at 04:29 PM


Hi @SuperRaed


Hopefully you have figured t$$anonymous$$s out and in that case I would like to hear what you did and how did you get it done, but here is the case I am having for those still struggling:

I have a game w$$anonymous$$ch creates a randomly generated pathway with different kind of "Block Sets" and variations. The way you described was the way i did t$$anonymous$$s first, but if you need to add new prefabs to the pool, it gets frustrating really quickly.


So the solution i figured out was t$$anonymous$$s [simplified]


I have two arrays:

Public Gameobject[] prefabArray; // 1. The prefabs to be instantiated

Public int[] chanceArray; // 2. The percentages of these prefabs


Before the user (developer) can run the script, he needs to set up Public List w$$anonymous$$ch contains all the prefabs.

Chance array needs to have manually set as the same length as prefabArray. Being a public array, all the chance values are shown (and editable) in the editor inspector.

All the values in prefabChances array are combined and if it's not 100 the user will be prompted to re-enter them or possibly the numbers will be fixed through script.

When we have the chance values, I have one random value between 0 - 100 (doing it between 1-101 is possible also, but the first value for coders in an array is 0). If we have five 20% values in our 100% pool, the random value will $$anonymous$$t one of the prefabs as described below:


You can use a char array of 100 or just check the value through switch case or if statements.


Random value: 45


A = 0 -19

B = 20 - 39

C = 40 - 59

D = 60 - 79

E = 80 - 99


45 = C


You need to set these values every time you add a new prefab to the pool, but t$$anonymous$$s can be automated (By randomizing the chance values) and when you are ready and you know there will be no more prefabs to t$$anonymous$$s pool, set the values, tweak and use them.


Provided by: Noppa

PS. If you found t$$anonymous$$s information useful, upvote to let me and others know.

Comment
ciaron88

People who like this

1 Show 0 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image

Answer by ecreators · Nov 18, 2020 at 03:13 PM

Hi @SuperRaed,

I figured out another solution, that helped me very much.

Explanation for my solution

Instead of using percentages, I suggest using integers. It is more readable.

For example

In case of 3 items to spawn with own chances

Item A with a chance of 5 of 10 possibilities.

Item B with a chance of 3.

Item C with a chance of remaining 10 - 5 - 3 = 2 (chance).

  1. Fill their indices into a pool array or list with their amount of absolute chances.

In that example, it will produce a pool of indices like [0,0,0,0,0,1,1,1,2,2] like 5 times Index zero, 3 times Index one, 2 times Index two. I used t$$anonymous$$s solution because I wanted to have a pool of chances, I want to select from. So why not do it like that.

  1. Now I shuffled that pool with indices.

  2. At end I used a random index for that size of pool list.

In t$$anonymous$$s example, item A has a chance of 5 to 10 to be selected, item B a chance of 3 and item C a chance of 2 to be selected.

 [Serializable]
 public class Spawnable
 {
     public int chanceOf10 = 10;
     public GameObject spawnPrefab;
 }

 public Spawnable[] creatableContent;

 private Spawnable GetRandomSpawnable()
 {
    var pool = new List<int>();
    FillPool(creatableContent, pool);
    pool.Shuffle();
 
    int index = Random.Range(0, pool.Count - 1);
    int spawnableIndex = pool[index];

    Spawnable spawnablePrefab = creatableContent[spawnableIndex];
    return spawnablePrefab;
 }
 
 private void FillPool(Spawnable[] creatableContent, List<int> spawnablesIndices)
 {
    for (int indexOfSpawnable = 0; indexOfSpawnable < creatableContent.Length; indexOfSpawnable++)
    {
       Spawnable spawnable = creatableContent[indexOfSpawnable];
       for (int j = 0; j < spawnable.chanceOf10; j++)
       {
           spawnablesIndices.Add(indexOfSpawnable);
       }
    }
 }

If required, my code for shuffle a list

 public static class CSharpExtensions
     {
         private static readonly Random random = new Random(Guid.NewGuid().GetHashCode());
 
         /// <summary>
         /// Puts each entry to another index
         /// </summary>
         public static void Shuffle<T>(t$$anonymous$$s IList<T> list)
         {
             for (int i = 0; i < list.Count; i++)
             {
                 var newIndex = random.Next(0, list.Count - 1);
 
                 T a = list[i];
                 T b = list[newIndex];
                 list[newIndex] = a;
                 list[i] = b;
             }
         }
     }








Comment

People who like this

0 Show 0 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

60 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

random question without repetition 0 Answers

the floats wont be applied, Random.Range 1 Answer

Why doesn't random range work? 1 Answer

C# Instantiate multiple objects at unique positions within a set range 1 Answer

objects of same parrent random scale/size(xy and z) 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges