Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by moonLite · Oct 31, 2012 at 08:01 PM · javascripttimertime.deltatimetime.timescaletime.time

Pause & Unpause Different timers

Hi Guys,

I have 2 timers, and I wish to pause them each at individually without affecting the other timer, and resume the time where it left.

Meaning, I would like to pause Timer A, while timer B continue to count down. and when I click Resume for Timer A, it will continue the remaining time where it left previously.

The Problem (I):
I'm using the Time.timeScale. But it's pausing the Time.time across the game scene. Basically, I tried to come out with have the same function with different name like `CountDown2 ()` And when I resume, Timer A's Remaining time is not continue which it last left.

For instance, if I pause Timer A's time, both timers, will be paused, if I unpause, both timers will resume with the different timing, it should be 12sec left, now it's 10sec (because of the Time.time)

Problem (II)

I can't pause each timer's time individually.


Qns 1) Is there any way I could pause just one timer only and left the other continue to count down? Qns 2) How do let the timer resume the time where it last left when I click the resume / unpause button? Qns 3) What are other areas I can improve my coding (below)?

Thanks in advance!

Below is my coding:

     var startTime : float; 
     var timeRemain : float;// time remaining
     
     var clockIsPause2: boolean = false;
     var startTime2 : float; 
     var timeRemain2 : float;// time remaining for timer 2
     
     function Awake()
     {
         startTime = 5;
         startTime2 = 10;
     }
     
     function Update () {
     
         
         if (!clockIsPause)
         {
             //Debug.Log("clock is not pause");
             CountDown ();
         }
         else
         {
             //Debug.Log("clock is PAUSEd);
         }
         
     if (!clockIsPause2)
     {
             //Debug.Log("clock is not pause");
             CountDown2 ();
         }
         else
         {
             //Debug.Log("clock is PAUSEd);
         }
      }
     
     function OnGUI ()
     {
          
         if (!clockIsPause)
         {
            if ( GUI.Button(Rect(350, 350, 100,30), "PAUSE"))
            PauseClock ();
          } 
       
        if (clockIsPause)
         {  
          if( GUI.Button(Rect(400, 350, 100,30), "Resume"))
         UnpauseClock ();
           }     
           
      
         if (!clockIsPause2)
         {
            if ( GUI.Button(Rect(350, 420, 100,30), "PAUSE2"))
            PauseClock2 ();     
         } 
       
        if (clockIsPause2)
         {  
          if( GUI.Button(Rect(400, 420, 100,30), "Resume2"))
         UnpauseClock2 ();
         }    
     }
     
     function CountDown ()
     {
         timeRemain = startTime - Time.time;
         
     }
     function CountDown2 ()
     {
         timeRemain2 = startTime2 - Time.time;
     }
     
     
     
     function PauseClock ()
     {
         clockIsPause = true;
         Time.timeScale = 0.0;
           Debug.Log("pause");
     }
     
     function UnpauseClock ()
     {
         Time.timeScale = 1.0;
         clockIsPause = false;
           Debug.Log("UNpause-ing");
     }
     
     function PauseClock2 ()
     {
         clockIsPause2 = true;
         Time.timeScale = 0.0;
         Debug.Log("pause2");
     }
     
     function UnpauseClock2 ()
     {
         Time.timeScale = 1.0;
         clockIsPause2 = false;
         Debug.Log("UNpause-ing2");
     }

For others searches, multi timers, multi-timer, multi-timers, different timers (since I can't add new key words)

Comment
Add comment · Show 4
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image AlucardJay · Nov 01, 2012 at 11:16 AM 1
Share

You are doing fine =]

The problem you are having here is using Time.time , this is universal. If you are just wanting to have 2 counters that can be independently paused, just use 2 counters, and add (or subtract) Time.deltaTime to these vars

e.g.

 #pragma strict
 
 var timer1 : float = 0.0;
 var timer2 : float = 0.0;
 
 var startTime1 : float = 5.0;
 var startTime2 : float = 10.0;
 
 var clockIsPause1: boolean = false;
 var clockIsPause2: boolean = false;
 
 
 function Start() 
 {
     timer1 = startTime1;
     timer2 = startTime2;
 }
 
 function Update() 
 {
     if ( !clockIsPause1 )
     {
         // decrease (countdown) timer
         timer1 -= Time.deltaTime;
     }
     
     if ( !clockIsPause2 )
     {
         // decrease (countdown) timer
         timer2 -= Time.deltaTime;
     }
     
     // check for timers running out
     if ( timer1 < 0 )
     {
         Debug.Log( "timer 1 ran out !" );
     }
     
     if ( timer2 < 0 )
     {
         Debug.Log( "timer 2 ran out !" );
     }
     
     // Reset timers    
     if ( Input.Get$$anonymous$$eyDown( $$anonymous$$eyCode.Alpha1 ) )
     {
         timer1 = startTime1;
         Debug.Log( "Resetting timer1" );
     }
     
     if ( Input.Get$$anonymous$$eyDown( $$anonymous$$eyCode.Alpha2 ) )
     {
         timer2 = startTime2;
         Debug.Log( "Resetting timer2" );
     }
 }


avatar image moonLite · Nov 01, 2012 at 02:53 PM 0
Share

@alucardj, thanks! thats pretty neat & simple!

Actually I wanted multi timer, the like a button click; new timer added event.

But I'm still new and if I ask too many things at once, I will get confused, I already get confused quite badly! So I break it into small chunks for my own understanding. :D

avatar image AlucardJay · Nov 02, 2012 at 01:23 AM 1
Share

Hi, no worries, it is very basic but steps out using a variable as a timer. The important parts are :

 timer = 0; // when initializing or resetting the timer for counting UP
 timer = timerStartTime; // when initializing or resetting the timer for counting DOWN
 timer += Time.deltaTime; // increment the counter with a real-time value
 timer -= Time.deltaTime; // decrement the counter with a real-time value.
 if ( timer > timer$$anonymous$$axTime ) {} // check for if UP counter has reached limit
 if ( timer < 0 ) {} // check for if DOWN counter has reached zero

The answer by @$$anonymous$$ontraydavis is excellent, I only just learned how to make and use a class struct, and it is very handy information.

The other discussion you both were having is about typecasting . Just imagine every variable has a type, int float String Vector3 etc etc.

The class is a type which you have created, so when you declare the variable playerTimer, just give it the type of TimerClass

Once I learned this, things got more fun !

Another example of typecastng variables to make things easier is using a script. Say yo have a script for a flashlight that has a public boolean isActivated, so the script runs itself, but you need to tell it when the player has pressed the F button on the PlayerScript. So say my light script is called FlashlightScript. In the PlayerScript,

 var myTorch : FlashlightScript;

now I can drop the Flashlight with the script FlashlightScript attached to it straight into the players inspector. Now you have access to all the public variables and functions on FlashlightScript from PlayerScript. For example, to turn the flashlight on :

 myTorch.isActivated = true;

Done, all without using Find. Though it is important to learn GameObject.Find and Transform.Find , as well as all the different methods of GetComponent.

But as I have only just learned how to comfortably use List, I really shouldn't be commenting =]

You are probably beyond all this, but here are some links I always pass on to other new Unity users, enjoy and Happy Coding =]

Starter Stuff, start at the bottom and work up : http://www.unity3dstudent.com/category/modules/essential-skills/

Start at the bottom and work up : http://www.unity3dstudent.com/category/modules/beginner/

this is the YouTube link for the above as one playlist : http://www.youtube.com/watch?v=-oXYHNSmTxg&list=PL27B696FB515608D2&feature=plcp

the Unity Wiki : http://wiki.unity3d.com/index.php/Tutorials

A list of resources : http://answers.unity3d.com/questions/12321/how-can-i-start-learning-unity-fast-list-of-tutori.html

Helpful page with information on using Built-In Arrays and Lists :

http://www.unifycommunity.com/wiki/index.php?title=Which_$$anonymous$$ind_Of_Array_Or_Collection_Should_I_Use?

The unity wiki link above is very handy with lots of scripts and shaders too (just check out all the links down the left, and the tabs along the top : http://wiki.unity3d.com/index.php/Scripts )

=]

avatar image moonLite · Nov 02, 2012 at 08:57 AM 0
Share

@alucardj,

Thanks for the information some i already have the links, but i still want to thank you so much for it.

I still don't understanding and unsure of the class, so I asked the a new question :D http://answers.unity3d.com/questions/341739/declaring-understanding-class-in-javascript.html

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by Montraydavis · Oct 31, 2012 at 09:09 PM

You have quite a bit of unnecessary stuff in there for one . . .

Try this multi-timer here!

 class TimerClass {
    var FirstTimer : float = 0 ;
    var FirstTimerActive : boolean = true ;
    var SecondTimer : float = 0 ;
    var SecondTimerActive = true ;
 }
 
 var PlayerTimer : TimerClass ;
 
 
 function Update ( )
 {
    if ( PlayerTimer.FirstTimerActive ){
       PlayerTimer.FirstTimer -= 1 * Time.deltaTime ;
       if ( GUI.Button(Rect(350, 350, 100,30), "PAUSE")){
          PlayerTimer.FirstTimerActive = false ;
       }
 
    }else{
       if( GUI.Button(Rect(400, 350, 100,30), "Resume") ){
          PlayerTimer.FirstTimerActive = true ;
       }
 
    }
 
    if ( PlayerTimer.SecondTimerActive ){
       PlayerTimer.SecondTimer -= 1 * Time.deltaTime ;
       if ( GUI.Button(Rect(350, 350, 100,30), "PAUSE2")){
          PlayerTimer.SecondTimerActive = false ;
       }
    }else{
       if( GUI.Button(Rect(400, 420, 100,30), "Resume2") )
       {
          Player.SecondTimerActive = true ;
       }
    }
 }
 
 function OnGUI ( )
 {
    if ( PlayerTimer.SecondTimerActive ){
       
       if ( GUI.Button(Rect(350, 350, 100,30), "PAUSE2")){
          PlayerTimer.SecondTimerActive = false ;
       }
    }
 
    if ( PlayerTimer.FirstTimerActive ){
       
       if ( GUI.Button(Rect(350, 350, 100,30), "PAUSE2")){
          PlayerTimer.FirstTimerActive = false ;
       }
    }
 }


That is a rought draft, and I apologize if there are any syntax errors! With having that said, you should now have two working Timers :) Good luck, and I hope this solves your issue .

Comment
Add comment · Show 6 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image moonLite · Nov 01, 2012 at 08:10 AM 0
Share

Thanks $$anonymous$$ontray!

It works. But I have a couple of questions about it.
1 ) Why function Update's part of the code and function OnGUI coding are almost the same?

2)In my code, I removed the function OnGUI coding, and move the function Update coding to function OnGUI area. Because unity returns an error; `ArgumentException: You can only call GUI functions from inside OnGUI.` Is there any work around with that error other than moving the coding to function OnGUI area?

3) class TimerClass is like a function but a independent bastket with a list of variables inside it, right?

4) If I wish to declare `var PlayerTimer` properly (long way) like `var abc : float = XXX; //(XXX is a var which previously declared value) or var timeRemain : float = 50;`, how should I declare? I want to learn it! :D

 var PlayerTimer : TimerClass ; // is the properly long way of declaring already?

I tried this "`var PlayerTimer : class = TimerClass;`" but it returns an error :D

Once again, thank you so much, $$anonymous$$ontray!



P.S. I just list the missing word error, so others can know the syntax error instantly next time.

Below is the $$anonymous$$issing word:

 PlayerTimer.SecondTimerActive = true;

Originally:

 Player.SecondTimerActive = true ;

And I also moved then function Update's coding to function OnGUI area. to make it works

avatar image Montraydavis · Nov 01, 2012 at 09:27 AM 0
Share

1) They essentially do the same, except the GUI calls .

2) Not really. All GUI calls need to be in OnGUI .

3) TimerClass is just structured data. JS equivalent to struct in C/C++/etc

4) You can declare them just as I did. All you need to do is just move the variable to your needs.

I am glad this helps, and let me know if you have other questions. Please mark as answered if you have gathered the information you need. Thanks for supporting Unity3D.

~$$anonymous$$ontray

avatar image moonLite · Nov 01, 2012 at 10:14 AM 0
Share

@$$anonymous$$ontraydavis

Thanks, I will mark it as answered once I ask and understand it all.

for 4) I do know that I could declare just like yours "var PlayerTimer : TimerClass ;"
but I'm just curious you know like proper declare for "`var abc : int =3;`" ins$$anonymous$$d of shortcut declaring var, "`var abc = 3;`"

Is there any for long proper for "`var PlayerTimer : TimerClass;`" like to into "`var PlayerTimer : [sometype] ; :TimerClass;`" or there is none?

I'm still new to unity & curious about it, so it would be good to learn the long proper way, though I may not use it :p

avatar image Montraydavis · Nov 01, 2012 at 12:15 PM 0
Share

This long/short way you think of really isn't required . . If you wish to define the variable type, you can do so ( jScript ).

 var PlayerTimer : TimerClass = new TimerClass ( ) ;
 or 
 var PlayerTimer = new TimerClass ( ) ;

Either works, though I suggest using the "long way" so that you know what everything is .

avatar image moonLite · Nov 01, 2012 at 01:26 PM 0
Share

@$$anonymous$$ontraydavis,

Thanks so the long way is

    var PlayerTimer : TimerClass = new TimerClass ( ) ;

I have a question about this class thing ( can i ask here, if not i will post a new question) I understand that class TimeClass is create a structure which contain a few data types like the code above.

But what I don't understand is var PlayerTime ( is a new var) : type(Timeclass) = new TimeClass();?

From my own assumption of understanding, it's like saying declaring a var,we called "baseball" : ball [type of object] = is a NEW BALL, is this how the code work? I'm a little confused and unsure about my own understanding. Please let me know if I get right, thanks!

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

11 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

timer starts in the menu scene 1 Answer

Countdown timer using Time.unscaledDeltaTime not working as expected. 1 Answer

Stealth AI Script. If less than or equal to not working correctly. Any fixes ? 1 Answer

Trouble with Time.Timescale 2 Answers

I cant get this timer to start when this bool turns true? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges