Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How Do you Count time in Scripting?

Discussion in 'Scripting' started by greatUnityGamer, Mar 23, 2015.

  1. greatUnityGamer

    greatUnityGamer

    Joined:
    Aug 11, 2013
    Posts:
    182
    I want an enemy AI.

    So the enemy starts of at standy.
    There should be a time counter which counts some random time.
    At that random time enemy should decide to or not decide to start walking.

    That's one example.
    The other example is if a character sets up a bomb.
    Let's say he grabs a bomb and then goes put it next to an enemy building and TUrns it on. At the time he turns it on...a TIMER should start counting time( From some value down to zero or from zero up a value)
    and when the TIME is up...an explosion should start.

    Anyways, how do you create these kind of Timers?
     
  2. TRG96

    TRG96

    Joined:
    Mar 26, 2011
    Posts:
    102
    You need to use Time.time to do what you want. Time.time increases in real world time. if you do a Debug.Log(Time.time) you will see it is going up in seconds so you can use this to do what you want.

    http://docs.unity3d.com/ScriptReference/Time-time.html

    If you look at nextFire = Time.time + fireRate; on Unity website, it is taking the time since the game was first started for example lets say its 15 seconds and it is adding fire rate which is 0.5f so the bullet will be fired and the next bullet will not be fired until Time.time is more than 15.5 seconds.
     
  3. Strategos

    Strategos

    Joined:
    Aug 24, 2012
    Posts:
    255
  4. greatUnityGamer

    greatUnityGamer

    Joined:
    Aug 11, 2013
    Posts:
    182
    Thank you. So if i use Time.time, is this gonna work??


    public void start(){
    myTime = Time.time + somerandomtime;
    }

    public void update(){
    if STATE = WAITING{
    if( myTime <= 0){
    If decide to walk
    STATE = WALK
    //create random amount of time to keep walking
    myTime = Time.time + somerandomtime;
    }
    else{
    //count down
    myTime = myTime - 1;
    }
    if STATE = WALK{
    (if myTime <= 0)
    STATE = WAITING;
    //Create random amount of time to keep waiting
    myTime = Time.time + somerandomtime;
    else{
    myTime -= 1;
    }
    }
    }
     
  5. greatUnityGamer

    greatUnityGamer

    Joined:
    Aug 11, 2013
    Posts:
    182
    Thank you so much. That sounds easy