Mark.S
Mark.S

Reputation: 165

if statement using && for two floats?

I have a c# script in Unity and have an issue. I'm trying to check if two floats equal to zero for a countdown timer. once both reach zero, do something.

when i do

if (minutes && seconds <= 0){
        Debug.Log("countdown timer has finished");
    }

I get the error;

error CS0019: Operator &&' cannot be applied to operands of typefloat' and `bool'

I understand what's going on here, my question is how can I check if both floats reach zero, debug.Log.

Upvotes: 0

Views: 2996

Answers (3)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26635

You can't check more than one variables like that. You must change your code:

if (minutes <= 0 && seconds <= 0){
        Debug.Log("countdown timer has finished");
    }

Or, if you have many variables to check like that, then you can create new List and use Any() method from th System.Linq namespace. (But, as @Marc commented if you have not a list yet, then it is not recommended):

if (!(new[] { firstFloat, secondFloat, thirdFloat }).Any(x => x > 0));

But, if you have a list or an array, it would be much better and simpler:

if (!myList.Any(x => x > 0));

Upvotes: 8

Ashish Singh
Ashish Singh

Reputation: 275

In C# You cannot do float comparison like this. In C++, boolean true is treated as non-zero value and for false it's zero. That's why we can directly compare the float value with in if condition. But in C# you have to specify the full condition.

if (minutes <= 0 && seconds <= 0){
        Debug.Log("countdown timer has finished");
    }

Upvotes: 0

AFract
AFract

Reputation: 9680

C# doesn't provide any syntax to combine application of single condition / operators on many variables directly in "if" condition (but of course you could do that with functions).

You have to test separately each condition :

if (minutes <= 0 && seconds <= 0)
{
   Debug.Log("countdown timer has finished");
}

You can also use a nicer datatype to handle all "time" related tests, such as Timespan, or even a "total seconds count" single variable. It's sounds strange to have separate "seconds" and "minutes" variables.

Upvotes: 1

Related Questions