problem if and timer

public float TimerBatteria = 20;
void Update (){
	  if(TorciaPresa){
	 //-------------------------------------------------------------- 
	    if(Torcia == true){
				//qui parte il timer della durata della batteria (collegata a TimerBatteria)
			if(TimerBatteria > 10) {
					
			light.intensity = PotenzaLuceDellaTorcia;
			TimerBatteria -= Time.deltaTime;
			}
			if(TimerBatteria == 0) {
			Torcia = false;
       	    light.intensity = 0;
			AudioSource.PlayClipAtPoint(SuonoBatterieScariche, transform.position, PotenzaVolume);
			BatteriaInserita = false;
			NumeroBatterie = NumeroBatterie - 2;
			TimerBatteria = 0;
					
			}
			if(TimerBatteria < 10){
				light.intensity = PotenzaLuceDellaTorciaRidotta;
				TimerBatteria -= Time.deltaTime;
				}

I have created a small timer through the use of if, but I give an annoying problem, when the variable TimerBatteria reaches 0 nothing happens and keeps going even under negative numbers, and I want that when I arrive at the 0 timer stops, how can I do?

You should never use == with floats. Use Mathf.Approximately() instead.

I’ve never used, and what should I put instead of if (TimerBatteria == 0)

This way you could stop at 0.0. I just made return; to stop it at 0.0. Sure you could do any possible stuff indtead of return;.

Your counter don’t check 0, because the last positive value is something like 0.2123 and the next is -0.1123 (just examples). You could see this in the debug log. So your if will never hit 0.0. My way is just to say everything after 0.0 is 0.0.

if(TimerBatteria <= 0.0f) {
			
                        // every value < 0.0f set to 0.0f
			TimerBatteria = 0.0f;
			Debug.Log ("It's 0.0! ***********************************************************" + TimerBatteria);
           
                         // do something here, reset counter to 20.00f for example
       		         return;
}

Normally I don’t work with deltatime, but others will kill me for writing this. :wink:

using UnityEngine;
using System.Collections;

public class guitests : MonoBehaviour {
	
	public float TimerBatteria = 20.0f;
		
	// Update is called once per frame
	void Update () {
	
		if(TimerBatteria > 10.0f) {

		Debug.Log (TimerBatteria);                
	        TimerBatteria -= Time.deltaTime;
		Debug.Log (TimerBatteria);  
        }

        if(TimerBatteria <= 0.0f) {
			
		TimerBatteria = 0.0f;
		Debug.Log ("It's 0.0! ***********************************************************" + TimerBatteria);
           
                // do something here
       		return;
        }

            if(TimerBatteria < 10.0f){

                Debug.Log ("It's < 10.0!" + TimerBatteria); 

                TimerBatteria -= Time.deltaTime;
			
		Debug.Log (TimerBatteria); 
			
             }	
			
	}
}

now it works perfect, thank you; =)

Welcome!

Yes so you did use == float, as TimerBatteria is a float.