If you want to continuously do something for a specific amount of time,you have to use Time.deltaTime in a coroutine. Increment a float value from 0 with Time.deltaTime until it reaches the time you want to do that thing.
IEnumerator executeInWithFixedTiming(float time)
{
float counter = 0;
while (counter <= time)
{
counter += Time.deltaTime;
//DO YOUR STUFF HERE
transform.Rotate(Vector3.right * Time.deltaTime);
//Wait for a frame so that we don't freeze Unity
yield return null;
}
}
You can start as many tasks as possible like below. The example run the code for 5 seconds:
StartCoroutine(executeInWithFixedTiming(5));
You can also extend this function and make it take a parameter of what to do in that coroutine as Action. You can then pass in the code to run inside that function too. Not tested but should also work.
IEnumerator executeInWithFixedTiming(Action whatToDo, float time)
{
float counter = 0;
while (counter <= time)
{
counter += Time.deltaTime;
whatToDo();
//Wait for a frame so that we don't freeze Unity
yield return null;
}
}
then use it like this:
StartCoroutine(executeInWithFixedTiming(
delegate
{
//DO YOUR STUFF HERE
transform.Rotate(Vector3.right * Time.deltaTime);
}, 5));
EDIT:
The thing is, I don't want to continuously do it for X seconds, but
only once at each point of Timings
You mentioned that the timer is sorted so a for loop to loop through it and while loop to wait for the timer to finish should do it.
List<float> timer = new List<float>();
IEnumerator executeInWithFixedTiming()
{
float counter = 0;
//Loop through the timers
for (int i = 0; i < timer.Count; i++)
{
//Wait until each timer passes
while (counter <= timer[i])
{
counter += Time.deltaTime;
//Wait for a frame so that we don't freeze Unity
yield return null;
}
//TIMER has matched the current timer loop.
//Do something below
Debug.Log("TIMER REACHED! The current timer is " + timer[i] + " in index: " + i);
}
//You can now clear timer if you want
timer.Clear();
}
Just start the coroutine once in the Start function and it should handle the timer. StartCoroutine(executeInWithFixedTiming());. You also also modify it with the second example in this answer to make it take a parameter of each code to execute.
Note:
In Unity, it's better to time something with Time.deltaTime. It's the most accurate way of timing that I know about. Other Unity variables tend to loose their accuracy over time.