Answers for "What is the most efficient way to spawn objects with probability weights in this scenario?"
http://answers.unity.com/questions/1618981/what-is-the-most-efficient-way-to-spawn-objects-wi.html
The latest answers for the question "What is the most efficient way to spawn objects with probability weights in this scenario?"Answer by jstopyraIGG
http://answers.unity.com/answers/1619038/view.html
I usually use Weighted Random for stuff like this. With weighted random, 100% is total of all chances combined, so you dont have to care about making the fruit add up to 100%.
In weighted random, you:
1) Add up all the weights to a sum
float sum = 0;
for(var fruit in fruits)
{
sum += fruit.spawnRate;
}
2) Generate a random number between 0 and sum(exclusive)
float randomWeight = 0;
do
{
//No weight on any number?
if(sum == 0)
return null;
randomWeight = Random.Range(0, sum);
}
while(randomWeight == sum)
3) Go through all items and check if the random number is less than the weight of that item. If it is not, then subtract that weight.
for(var fruit in fruits)
{
if(randomWeight < fruit.spawnRate)
return fruit;
randomWeight -= fruit.spawnRate;
}
Your code should never go this far
return null;Thu, 04 Apr 2019 18:36:47 GMTjstopyraIGGAnswer by Tsaras
http://answers.unity.com/answers/1618995/view.html
You can easily do what you want with 2 parallel arrays. Let's say you have an array of probabilities for each fruit like the ones you mentioned. You also have an array of gameobjects that correspond to the probabilities index by index. You can then create a cumulative array at runtime to do your business:
GameObject[] fruit;
float[] probability; //40% could be 0.4f
float[] cumulative;
void MakeCumulative() //this function creates the cumulative array
{
float current = 0;
int itemCount = probability.Length;
for(int i = 0; i <= itemCount; i++)
{
current += probability[i];
cumulative[i] = current;
}
if (current > 1.0f)
{
Debug.Log("Probabilities exceed 100%");
}
}
GameObject GetRandomFruit()
{
float rnd = Random.Range(0, 1.0f);
int itemCount = cumulative.Length;
for(int i = 0; i <= itemCount; i++)
{
if (rnd <= cumulative[i])
{
return fruit[i];
}
}
return null;
}Thu, 04 Apr 2019 15:24:17 GMTTsaras