Using function return in if statement

Hey,

Just wondering if using a function’s return in an if statement for example is fine, or if it’s something i should avoid doing and use a variable instead? I’m learning about function return values which is something i never bothered using.

void Start()
{
    if(RandomBool())
    {
        //Do something;
    }
}
 
bool RandomBool()
{
    return Random.value > 0.5f ? true : false;
}

Thanks

Of course it is correct, this is a typical use of a function. Basically you will have an “invisible” variable that is created for the return of the function. This saves you some lines and memory allocation for a local variable (although it might be optimized away by the compiler). It can also be easier to read, for example if you have a function IsVisible(), writing if (IsVisible())is very easy to understand.

Did you test and see if it works? There’s nothing wrong with it. No reason to create a variable only to return it on the next line…