[C#] Rare chances

How can I create a rare chance generator in my script so that if the player gets a score of 10 an animation plays.
Using my IncreaseScore() component.

public void IncreaseScore()
    {
        {
            Score = Score + 1;
            SetScoreText();
        }

        if (Score == 10)
        {
            SpawnController SC = GameObject.Find("SpawnManager").GetComponent<SpawnController>();
            SC.DoubleSpawn1();
        }

        if (Score == 10)
        {
            // 1 in 100 chance generator
              anim.SetTrigger("SomethingHappens");         
        }
    }

Ask me if you need more information.

I personal would change the script to:

public void IncreaseScore()
{
     Score += 1;
     SetScoreText();
     if (Score == 100)
     {
          SpawnController SC =     GameObject.FindGameObjectWithTag("Its tag here").GetComponent<SpawnController>(); //I used Find Tag for optimization
         SC.DoubleSpawn1();
         int chance = Random.Range(1f, 100f);
         if(chance == 33)//33 because it has the chance on being 33 only one time.
        {
               anim.SetTrigger("SomethingHappens");
        }
     }
}

I can’t test it in Unity because I am at school but this should work. May be some typos check it please. Also you should start it in a coroutine called in the Start method.

1 Like

The typical way to make something happen occasionally is to use the Random class. I would use Random.value and check that it is less than a certain value. Random.value returns a random number between 0 and 1, so checking if it is less than 0.01 would result in a 1% chance of being true. Something like this:

if (Score == 10)
{
  SpawnController SC = GameObject.Find("SpawnManager").GetComponent<SpawnController>();           
  SC.DoubleSpawn1();
  if (Random.value < 0.01)
    anim.SetTrigger("SomethingHappens");
}

Browdaddy96 's code is almost right except you will need to use the integer version of Random.Range and will want the values 0, 100 instead of 1, 100

int chance = Random.Range(0, 100);

Anyways, I still prefer testing if a value between 0 and 1 is less than some percentage because it is more clearly related to testing of percentages.

1 Like

Thanks guys, really appreciate the help!