Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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 /
avatar image
1
Question by Kensei · Sep 02, 2014 at 06:10 PM · c#randomchancespaw

Spawn chance in my spawner.

Hi guys, I'm trying to have my spawner work depending on the spawn chance of the object. I just can't figure out how to influence the pick. Here's my current code:

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class Spawner : MonoBehaviour {
 
     public Item[] items;
 
     private Transform MyTrans;
 
     void Start () 
     {
         MyTrans = transform;
         StartCoroutine(Spawn());
 
     }
     
 
     void Update () 
     {
     
     }
 
     IEnumerator Spawn()
     {
         while (true)
         {
             Vector3 drop = new Vector3 (MyTrans.position.x + Random.Range(GameController.GM.minX + 0.2f,GameController.GM.maxX - 0.2f), MyTrans.position.y,0f);
             Instantiate (currentSpawn(),drop,Quaternion.identity);
             yield return new WaitForSeconds(Random.Range(0.5f,1.5f));
         }
     }
     private Item currentSpawn()
     {
         float chance;
         foreach (Item item in items) // retrieve the spawn chance from the item array.
         {
             chance = item.spawnChance;
         }
 
         Item theSpawn = items[Random.Range(0,items.Length)];
         return theSpawn;
     }
 }

Any ideas? I'm just want to have different spawn rates for my objects, higher point awards spawned less frequently than low score.

Comment
Add comment · Show 2
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 kacyesp · Sep 02, 2014 at 06:15 PM 0
Share

I have an idea but will items ever change after the Start() function is called?

avatar image Kensei · Sep 02, 2014 at 06:35 PM 0
Share

nope, I just came up with something:

 private Item currentSpawn()
     {
         float random = Random.Range(1f,100f);
         Item theSpawn = null;
         foreach (Item item in items) // retrieve the spawn chance from the item array.
         {
             if(item.spawnChance <= random)
             {
                 theSpawn = item;
             }
         }
         if(theSpawn!=null)
         {
             return theSpawn;
         }
     }

But I get a "Not all paths return a value" xception.

2 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by kacyesp · Sep 02, 2014 at 06:43 PM

Edited. Here's a much more efficient implementation and probably exactly what you want in terms of "chance". Since you said your items never change after the Start function is called, I just made an array to represent the range of chance that each item falls into. Using the random number generator, whatever range of chance the randomly generated number falls into, then the item corresponding to the range will be returned. What makes this much more efficient is that I use a binary search compared to a linear search. If you have N items, then this algorithm will take at most log( N ) operations. Using a linear search would take at most N operations. Imagine if you had 1024 items. That's 1024 operations. But log( 1024 ) is only 10 operations :)

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 using System;
  
 public class Spawner : MonoBehaviour {
  
     public Item[] items;
     public Tuple<float,float>[] itemChance;
  
     private BinarySearchComparer binarySearchComparer;
  
     private Transform MyTrans;
  
     void Start () 
     {
         MyTrans = transform;
  
         float totalChance = 0;
  
         for ( int i = 0; i < items.Length; ++i ) 
             totalChance += items[i].spawnChance;
  
         float beginningOfChance = 0;
         float endOfChance = 0;
         itemChance = new Tuple<float,float>[items.Length];
  
         for ( int i = 0; i < items.Length; ++i ) {
             endOfChance = beginningOfChance + item.spawnChance / totalChance;
             itemChance[i] = new Tuple<float,float>(beginningOfChance, endOfChance );
             beginningOfChance = endOfChance;
         }
  
         binarySearchComparer = new BinarySearchComparer();
  
         StartCoroutine(Spawn());
  
     }
  
  
     void Update () 
     {
  
     }
  
     IEnumerator Spawn()
     {
         while (true)
         {
             Vector3 drop = new Vector3 (MyTrans.position.x + Random.Range(GameController.GM.minX + 0.2f,GameController.GM.maxX - 0.2f), MyTrans.position.y,0f);
             Instantiate (currentSpawn(),drop,Quaternion.identity);
             yield return new WaitForSeconds(Random.Range(0.5f,1.5f));
         }
     }
     private Item currentSpawn()
     {
         float chance = Random.Range(0, 100);
         int index = Array.BinarySearch( itemChance, chance, binarySearchComparer );
         return items[index];
     }
  
     public class Tuple<T,U>
     {
         public T Item1 { get; private set; }
         public U Item2 { get; private set; }
 
         public Tuple(T item1, U item2)
         {
             Item1 = item1;
             Item2 = item2;
         }
     }
  
     private class BinarySearchComparer : IComparer<Tuple<float, float>>, IComparer
     {
         public int Compare( float chance, Tuple<float, float> changeRange)
         {
             if ( chance <= chanceRange.Item1 )
                 return -1;
  
             if ( chance > chanceRange.Item2 )
                 return 1;
  
             return 0; 
         }
     }
  
 }









Comment
Add comment · Show 8 · 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 Kensei · Sep 02, 2014 at 06:45 PM 0
Share

Then I get a null xception sometimes.

avatar image kacyesp · Sep 02, 2014 at 06:49 PM 0
Share

Then you most likely have an empty items list.

avatar image Kensei · Sep 02, 2014 at 09:19 PM 1
Share

Wow, thank you very much. It took me a while to comprehend the whole thing but it it works very well. I have to say this is a bit higher level code than my current understanding of C#, but nevertheless good stuff. Again, thanks. It seems smart to use a tuple for this particular case. Wouldn't have worked if my spawn array was a dynamic list or something.

avatar image Kensei · Sep 03, 2014 at 04:27 AM 1
Share

wow, 7 hrs later and u got 1.1k Ur goin up sky high :D

avatar image Scribe · Sep 03, 2014 at 01:14 PM 1
Share

Really nice answer @kacyesp and nice to see a new active user! :D +1 from me

Show more comments
avatar image
1

Answer by Scribe · Sep 02, 2014 at 06:42 PM

Hey there, this should work for you:

 public Item[] items;
 float totalInfluence;
 
 void Start(){
     totalInfluence = CalcInfluences(items);
 }
 
 void Update(){
     Debug.Log(RandomInfluencedIndex(items));
 }
 
 float CalcInfluences(Item[] items){
     float sum = 0;
     foreach(float i in items){
         sum += i.spawnChance;
     }
     return sum;
 }
 
 int RandomInfluencedIndex(Item[] items){
     float rand = Random.Range(0f, totalInfluence);
     float tempSum = 0;
     for(int i = 0; i < items.Length; i++){
         tempSum += items[i].spawnChance;
         if(rand <= tempSum){
             return i;
         }
     }
     return items.Length-1;
 }

currently it is setup to return the index of the item that was randomly selected, but you could quite easily swap it to just return the actual item!

Scribe

Comment
Add comment · Show 3 · 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 Kensei · Sep 02, 2014 at 06:48 PM 0
Share

Fascinating. Thanks, I will give it a go once I completely give up on my approach :)

avatar image Scribe · Sep 02, 2014 at 07:12 PM 1
Share

Sure, there are always several ways of doing anything! I just realised it would be very slightly more efficient to $$anonymous$$us the spawnChance from the random number rather than having another sum variable, like so:

 int RandomInfluencedIndex(Item[] items){
     float rand = Random.Range(0f, totalInfluence);
     for(int i = 0; i < items.Length; i++){
         if(rand <= items[i].spawnChance){
             return i;
         }
         rand -= items[i].spawnChance;
     }
     return items.Length-1;
 }


Enjoy!

avatar image Kensei · Sep 02, 2014 at 09:20 PM 1
Share

Well, I ended up using kacyesp's code, but I gave your solution a run as well and it worked too. You guys are amazing thank you all ^^

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.

Follow this Question

Answers Answers and Comments

24 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

Related Questions

Random.value not working properly? 1 Answer

probability of child Game objects 1 Answer

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Modify mesh problems 1 Answer


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