Problem with my IF statement

Hi I’m new to unity coding and I’ve wrote this code to switch the light smoothly with pressing the button,
but my problem is my bool (alarmON) won’t turns to false after the process,
would you please help me to make it works great
thank you
Here is my code:

public float intensityfadeSpeed = 2f;
    public float highIntensity = 2f;
    public float highStrength = 1f;
    public float shadowFadeSpeed = 2f;
    public bool alarmOn = false;                 

   
   
    void Awake ()
    {

        GameObject.Find("Directional light").GetComponent<Light>().intensity = 0f;

    }

    void OnClick()
    {
        alarmOn = true;
    }

    void Update () {

        if (alarmOn == true)
        {
            GameObject.Find("Directional light").GetComponent<Light>().intensity = Mathf.Lerp (GameObject.Find("Directional light").GetComponent<Light>().intensity, highIntensity, intensityfadeSpeed * Time.deltaTime);

            GameObject.Find("Directional light").GetComponent<Light>().shadowStrength = Mathf.Lerp (GameObject.Find("Directional light").GetComponent<Light>().shadowStrength, highStrength, shadowFadeSpeed * Time.deltaTime);

            stopChanging();

        }
       
    }
   
    void stopChanging ()
    {
        if (GameObject.Find ("Directional light").GetComponent<Light> ().intensity == highIntensity && GameObject.Find ("Directional light").GetComponent<Light> ().shadowStrength == highStrength)
        {
            Debug.Log("bullsEye");
            alarmOn = false;
        }
    }

}

Line 37
Comparing floats with == is genrally a bad idea, because one of the values might be 99.99999999 and the other is 100.0000000 = they are not equal
change to ‘above a threshold’ and it should work.
if(xxx > highIntensity - smallNumber … )

You should use Mathf.Approximately to compare float variables. Also don’t use GameObject.Find every frame because it’s very slow. Make a public Light variable and assign it in the inspector.

1 Like

Can you tell me how can i use Mathf.Approximately in my if statement with lights intensity?? thank you so much i really appreciate it

public Light dirLight;
public float highIntensity;
public float highStrength;

private void stopChanging()
{
    if(Mathf.Approximately(dirLight.intensity, highIntensity) && Mathf.Approximately(dirLight.shadowStrength, highStrength))
    {
        alarmOn = false;
    }
}

I suggest you read some tutorials on Coroutines. A Coroutine would be much better for what you are trying to do.

1 Like

Thank You So Much Really appreciate it