# Loop for a certain amount of time?

I’m trying to loop in something like a for loop for a time? I’m not sure how to write the for loop as I can’t seem to get it to work unless I have something like for(var i; i < 10; i ++) but I need something like for(Time.time < endTime) ?? this is my current code:

``````#pragma strict
var shake = false;
var shakeTime : float;

function OnGUI()
{
if (GUI.Button(Rect(Screen.width / 2 - 50,25,50,25),"ShakeIt!"))
{
print("" + Time.time);
Shake(shakeTime);
}
}

function Shake (lengthTime : float)
{
var endTime = Time.time + lengthTime;
while(Time.time < endTime)
{
transform.position = Vector3( Mathf.Repeat(Time.time, 0.1), Mathf.Repeat(Time.time, 0.1), transform.position.z);
}
}
``````

Is ur above code works correct?

No, my current code crashes Unity.

what exactly u need please explain a bit?

i don;t use ongui stuff. however i best guess would be that you are looping waiting for a time that the system can’t possibly get to because it is looping.

you basically created an infinite loop.

i would do the following…

``````bool doShake = false
float stopTime = 0.0f;
bool btnCanBeClicked = true;
OnGUI()
{
if(btnClicked  btnCanBeClicked)
{
stopTime = Time.currentTime + offset;
doShake = true;
btnCanBeClicked = false;
}
if(doShake)
{
Shake();
}
}

Shake()
{
if(time.currentTime >= stopTime)
{
doShake = false;
btnCanBeClicked = true;
stopTime = 0;
}

transform.position = shake magic
}
``````

Thanks guys for the input, this is my solution:

``````static function ShakeFunction (lengthTime : float, shakeTransform : Transform)
{
var endTime = Time.time + lengthTime;
while (Time.time < endTime)
{
shakeTransform.position = Vector3( Mathf.Repeat(Time.time, 0.1), Mathf.Repeat(Time.time, 0.1), shakeTransform.position.z);
yield;
}
}
``````

It may be worth looking at implementing an IEnumerable function (co-routine), as I have a suspicion this solution will be hanging your thread. (Unless JS manages the return type from the yield).

Yes, using co-routines its the best way, with: yield return new WaitForSeconds (whatever-time-you-need) <–this is in C#

However, not the ONLY way. Maybe also not the most elegant one.

There is a free open-source plugin which enables asynchronous programming with Unity - eDriven.

You could use the Timer class like in this example.

Before running the example, you have to download eDriven framework - here are the DLLs.

The Timer class is being used like this:

``````public class TimerTest : MonoBehaviour {
private Timer _timer;
void Start()
{
Debug.Log("Start");
_timer = new Timer(1); // tick each second
_timer.Tick += TickHandler; // subscribe
_timer.Start();
}
void TickHandler(Event e)
{
Debug.Log("Tick!");
}
void OnDestroy()
{
Debug.Log("OnDestroy");
_timer.Tick -= TickHandler; // unsubscribe
_timer.Stop(); // stop the timer
_timer.Dispose(); // dispose
}
}
``````