0

So I have 4 GameObjects that are currently spawning Randomly.

1.Regular Platform 2.Spiky Platform 3.Bouncy Platform 4.Coin Platform

So the problem is that it is spawning RANDOMLY. PROBLEM How can I add or control the spawning probability of each platform. Code wise. C#

Like within 10sec of play time. 85% chance of spawning Regular Platform 5% chance of spawning spiky platform 5% chance of spawning bouncy platform 5% chance of spawning coin platform

Note that the platform is spawning every seconds in the game.

derHugo
  • 83,094
  • 9
  • 75
  • 115

1 Answers1

0

You could do something like that.

/// <summary>
/// Returns random index of a finite probability distribution array
/// </summary>
/// <param name="prob"></param>
/// <returns></returns>
public static int PickOne(float[] prob)
{
    int index = 0;
    float r = UnityEngine.Random.value;

    while (r > 0)
    {
        r -= prob[index];
        index++;
    }
    index--;

    return index;
}

This gives you a random index based on the probability distribution with final support. So if you call

int index = PickOne(new float[] { 0.85f, 0.05f, 0.05f, 0.05f });

index would be the random index value (in this case between 0 and 3 inclusive) based on the probability distribution you gave.

Dharman
  • 30,962
  • 25
  • 85
  • 135
SushiWaUmai
  • 348
  • 6
  • 20