Search Unity

How to Get a Variable to Increase?

Discussion in 'Scripting' started by JVGameDev, Mar 20, 2017.

  1. JVGameDev

    JVGameDev

    Joined:
    Oct 5, 2015
    Posts:
    137
    Hi! I want my timer variable to increase by 1.5 every second. How do I do this?
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,187
    If you have a float that is keepng track of time, then you either set up a invokerepeating to increment it every second by 1.5, or you use a coroutine with a loop that will wait for 1 sec and then increment it by 1.5. I suggest the coroutine version personally.
     
  3. JVGameDev

    JVGameDev

    Joined:
    Oct 5, 2015
    Posts:
    137
    Hmm, isn't there something where you can just do
    timer += 1.5;
    Or is that Game Maker stuck in my mind?
     
  4. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,187
    Of course, but you have to have a way of telling it when to do that. Otherwise, how would it know you want to add 1.5f every 1 second?

    A coroutine does that by letting you declare a wait time, then add 1.5f to your timer. Then because you want it in a loop, it will loop and wait 1 sec before adding again.

    timer +=1.5f will add the value once and nothing wrong with that line, just need to include the logic
     
  5. Laperen

    Laperen

    Joined:
    Feb 1, 2016
    Posts:
    1,065
    I'd go with a Coroutine or invoke repeating for the convenience of it since it is a function which does a thing every time interval. You wouldn't even need the variable to increase.

    If you are still hell bent on using a variable instead, you could do this on Update. It may work but really isnt ideal.
    Code (CSharp):
    1. public float timeInterval//would be set to 1.5 in the inspector
    2. float currTime//the variable to use for whatever it is you are doing
    3.  
    4. void Update(){
    5.     currTime += Time.deltaTime;
    6.     if(currTime >= timeInterval){
    7.         //do stuff
    8.         currTime = 0;
    9.     }
    10. }