reseting timer unity

by Laurenz Kaml   Last Updated October 09, 2019 15:13 PM

So I have been trying to reset this timer but for some reason I can't figure out why it isn't resetting.

Thanks,

public class controlborder : MonoBehaviour
{
    //varibles
    public static int time; //<== here I create my timer
    public static int random;
    public static bool boolreset = true;
    //varibles
    //get objects
    public SpriteRenderer m_spriteRenderer;
    //get objects

    public void Start()
    {
        m_spriteRenderer = this.GetComponent<SpriteRenderer>();
        StartCoroutine(Changecolortimer(2f));
    }

    IEnumerator Changecolortimer(float loopdaelay)
    {
        while (boolreset)
        {
            yield return new WaitForSeconds(1);
            time++; //<== here is set a interval
            if(time == 3)
            {
                boolreset = false;
                resettime();
            }
        }
    }
    public void changeColor()
    {   
        if (random == 1 && time == 1)
        {
            m_spriteRenderer.color = Color.blue;
        }
        else if (random == 2 && time == 2)
        {
            m_spriteRenderer.color = Color.red;
        }
        else if (random == 3 && time == 3)
        {
            m_spriteRenderer.color = Color.green;
        }
        else if(random == 4 && time == 4)
        {
            m_spriteRenderer.color = Color.yellow;
        }
    }

    public void Update()
    {
        random = Random.Range(1, 4);
        changeColor();

    }

    public void resettime()
    {
        time += 0;
        boolreset = true;
        Debug.Log(time);
    }
}
Tags : unity c#


Answers 1


In your resetTime function you are using the "+=" operator, which adds onto the variable's current value, rather than assigning it directly to the specified value. See this example to understand the difference between += and = operators:

int x = 1 //declaring int, initial value is 1
x += 5    // this evaluates to "x = x + 5", so x's value is now 6
x = 999   // this evaluates to "x = 999", setting x's value directly to 999

In the resetTime() method you are adding 0 to the current value of time, not setting time to 0. Change that line to use the = operator instead of the += operator and you should get the desired behavior.

disc_code22
disc_code22
October 09, 2019 14:23 PM

Related Questions


Updated July 02, 2019 11:13 AM

Updated July 12, 2015 13:05 PM

Updated July 13, 2015 13:05 PM