How can i stop value incresing

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class vALUEtEST : MonoBehaviour {


    public float testValue = 10f;
    private float add = 10f;


    // Use this for initialization
    void Start () {
       
    }
   
    // Update is called once per frame
    void Update () {


        if (Input.GetMouseButton (0)){
            testValue = Time.time + add;
        }

        if (Input.GetMouseButtonUp (0)){
                testValue -=0.1f;
            }
       
    }
}

i have a basic script where when i press the mouse button the value in the inspector increases, when release button value stops increasing but if you wait a while then press the button again you will see that the value jumps up, so the value has been increasing even when the button is not pressed, how can i pause the increase when the button is released then restart it when button is pressed, i have to use the time.time as this is what is in the script i am using for my game, the script i have here is just a basic recreation to show the problem.

i think there must be a way but cant find it, i have tried to store the value into another variable when the button is not pressed then restore it when pressed but it still does not stop the increase

just add code to empty object, values show in inspector

any help appreciated

Hard to say without sharing the code. Somewhere in the code you’re increasing the value when the button is not pressed. Somehow change that code so it doesn’t do that.

The value of Time.time never goes down, it always goes up, even when you’re not pressing the button. When you push the button the second time, your code causes the value to “catch up” with the time that has continued to progress. You do not want to use Time.time at all, if you need to stop the testValue progress.

Change line 22 to testValue += add; and see the difference. You may need to adjust your value of add to be quite small. Or, testValue += Time.deltaTime * add; to scale the movement slowly and smoothly according to your machine’s frame rate.

2 Likes