if statement with floats in C#

Hello i was writing a simple if statement in C#, and Unity gave me an error.
To be more specific the error was in the if statement:

if (timeLeft = 0){
timeLeft = 5;
}

But i do not now wath’s wrong.
Can someone please help me ? My script is below.
There is also a picture of the error below.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class CountDown : MonoBehaviour {

    public Text timeText;

    private float timeLeft = 5;
    private int destroyerTimer;

    void Awake ()
    {
       
    }

    void Start ()
    {
        timeText.text = "";
    }

    void OnTriggerEnter (Collider other)
    {

        if (other.gameObject.CompareTag ("Pick Up2"))
        {
            destroyerTimer = destroyerTimer + 1;
            StartCoroutine (processTask4 ());
        }

    }
   
    void Update ()
    {
        if (destroyerTimer > 0)
        {
            timeLeft -= Time.deltaTime;
            timeText.text = "time left:" + Mathf.Round (timeLeft);

            if (timeLeft < 0)
            {
                timeText.text = "";
            }
        }

        else
        {
            timeText.text = "";
        }

        if (timeLeft = 0)
        {
            timeLeft = 5;
        }
    }

    IEnumerator processTask4()
    {
        yield return new WaitForSeconds (5);
        destroyerTimer = destroyerTimer - 1;
    }
}

Oh i was just about to post: Using code tags properly

but part of your post has code properly! excellent. Always use that format for code, in the future please :slight_smile:

The problem is you’re using assignment instead of comparison. Check it says ‘timeLeft = 0’ instead of ‘timeLeft == 0’
Change it and all is well.

2 Likes

Thank you mister methos5k.
I will remmeber this for the next time i need an if statement with a float.
But for now i found an other working solution, where i doesn’t has to use this statement.

comparing a float with another number is just going to lead to problems due to rounding errors
use something like

if (timeLeft <= 0)
if ( (timeLeft-0)*(timeLeft-0) < 0.00001f )

For sure, using <= 0 would have been better. I was focused on the error, but that is important to note :slight_smile:

1 Like