Hello everyone,
I would like to understand how this code works:
myBool=(Random.value > 0.5f);
Random.value create me a random float between 0 and 1, and I ask if the value is greater than 0.5.
Does this mean that a bool has a float value between 0 and 1, and that intermediate values are interpreted as 0 or 1??
No. All itās asking is āis this expression true or falseā.
Ergo, is this random value between 0 and 1 greater than 0.5? If yes, the boolean is true, otherwise itās false.
Itās more or less the same as:
bool myBool;
if (Random.value > 0.5f)
{
myBool = true;
}
2 Likes
I understand what you want to tell me, except that I used it like that. And it works :
Test you will see.
bool myBool;
public void()
{
myBool= (Random.value > 0.5f);
if (myBool)
{
...
}
else
{
...
}
}
Maybe itās used so much that the Devs integrated it.
What? No. Did you listen to me at all? Itās just a C# thing.
Basically boolean = (boolean expression)
3 Likes
A ok, I understand better, I donāt know the boolean expression. As my code worked, I donāt understand why, thanks
In short, the ā>ā sign is an operator that takes two numeric operands and returns a boolean value. So either true or false. This boolean value you simply assign to your boolean variable. Some people think that those operators somehow belong inside if statemens only. However those are just comparison operators and can be used anywhere a boolean value is required. You can think of operators like a special notation for methods. So this
c = a > b
would be the same as this:
c = IsGreaterThan(a, b)
This fictitious method āIsGreaterThanā would have a signature like this:
public bool IsGreaterThan(float num1, float num2)
It returns true whenever the first number is greater than the second number. Thatās what the >
operator does.
An if statement on the other hand just requires a boolean value and does not need to include any of those operators if you already have a boolean value. Thatās why if statements like this
if (myBoolVariable == true)
are redundant. You could just do
if (myBoolVariable)
instead.
In your specific case you assign a random boolean value to your variable. Random.value returns a uniform random number between 0 and 1. Since itās uniformly distributed, half of the time the value would be greater than 0.5 and half the time it would be below 0.5. So this expression āconvertsā all random values greater than 0.5 to ātrueā and any value smaller than (or equal to) 0.5 to āfalseā.
I donāt know how we can explain it any simpler :). Maybe you want to look up some boolean algebra basics. Also look up comparison operators if you have trouble understanding them. Those are the most essential parts of pretty much any programming language
3 Likes
Thank you for the explanation, itās simple and effective.