Heads or Tails? Flipping a coin


How do you flip a coin? In code? Elegantly?

I don’t mean the model, but returning a random boolean value?

Well, it’s not that simple… or, really… it is.

I needed a quick bit of code to get a random range for what is essentially Heads or Tails, and I felt that Random.Range (0, 2); and then testing this somehow was a bit ugly.

This seemed a bit more elegant:

bool orientation = (Random.value > 0.5f);

Random.value returns a random float number between 0.0 [inclusive] and 1.0 [inclusive], so we simply need to check whether it’s greater or less than a 50% chance of the returned value, or 0.5f.


The Random class includes a few other goodies that can be used in clever ways…


… but we’ll get to that soon enough.

No Comments

Leave a Comment

Please be polite. We appreciate that. Your email address will not be published and the required fields are marked.