- Home /
How to count seconds while mouse is pressed?
I have a very simple problem, but I trough it should be easier.
What I need is:
1 - While some mouse button is pressed, a counter starts running on a loop, it goes from 1 to 5. When the counter reaches 5, it stars again from 1.
What I've done already:
1 - I can detect when mouse button is pressed and released whitout any problem. So that's not a problem.
2 - I tried to make a loop using "for" and later "while" but Unity3D crashes. So I tried time.deltaTime, but I don't know how to count the time while mouse is pressed.
If you share your code, we can tell you what is causing the infinite loop.
var timeIsUp : float = 5.0 ;
var timeNow : float = 1.0 ;
function timer(){
if(timeNow >= timeIsUp){
timeNow = 1 ; }
if(timeNow < timeIsUp){
timeNow += Time.deltaTime ; }
Debug.Log(timeNow) ;
}
I put this in a comment because my answers take an hour or more to get posted since I'm a No0b in this website, and this is a short one so whatever. Just put this in whatever function you're wanting to call it in (change the function name, obviously, to whatever you're using).Not sure if you want it to display the count on the screen or what, but this will do what you asked for. Just tweak it for whatever else....
Answer by jahroy · Dec 14, 2011 at 03:07 AM
Here is how you would count how long it's been since a button was clicked.
var buttonPressTime : float = 0.0;
var buttonRect : Rect = Rect(200, 200, 120, 40); var labelRect : Rect = Rect(200, 240, 120, 40);
function OnGUI () { if ( GUI.Button(buttonRect, "Start Timer") ) { buttonPressTime = Time.time; }
var timeSince : float = Time.time - buttonPressTime;
GUI.Label(labelRect, "Time since: " + timeSince);
}
Thanks man! That really helped , I use C# and wanted to adapt with a key press ins$$anonymous$$d of mouse button . I was having trouble with the update Function , but with some tweeking I finally did it.