How to set a cast?

{

    float timeleft = 600;

    void Update ()
   
    {
        timeleft -= Time.deltaTime;
        Debug.Log(timeleft);
       
    }
}

This simple code counts down in seconds, but displays it as a long float. How do I cast timeleft as an integer or display it as an integer? By changing float to int I get an error saying ‘are you missing a cast?’

Casting is when you force one data type to become another. When you change timeleft to an Int you’re trying to put a float (deltaTime) into an Int and the compiler wonders if you’ve missed a cast. To cast it, you do this:

timeleft -= (int)Time.deltaTime;

Although with what you’re doing, you’re probably better keeping the timeleft as a float and formatting the display part:

Debug.Log(timeleft.ToString("F0"));

This makes it display as a Floating point number with 0 decimal places.

1 Like