Need help with probability...

I have a script that sets a variable to a value between 1 and 0 (such as 0.366). What I want to do is then perform a function with the probability of it happening being equal to this variable (e.g 1.0 means it will do it every time, 0.5 means it has a 50/50 chance of doing it).

Is there an inbuilt Unity function to do this? Or is there a mathematical trick to this?

If it helps, I’m working in javascript.

Sure, you can do that. Suppose you have probability, which is your variable between 0 and 1. Then run a task with probability chance of running:

if (Random.value <= probability)
    RunSomeTask();

This works because Random.value returns a random between 0 and 1, so if for example your probability is 0.2, Random.value ideally has a 20% chance of being smaller than 0.2.

The simplest way would be to use Random.value. Something like

if(Random.value >= probability) CallMyFunction();

Where probability is the desired chance threshold (e.g. if you set it to 0.5 then theoretically the random would cause the function to be called half the time).

It’s worth mentioning that Unity’s internal Random class isn’t extremely random, so you might want to re-seed it every time to increase the randomness factor, or use another random library.

A seed effects the random method so that if you input the same seed each time, you should get the exact same result each time.