- Home /
Time Manager Class Implementation Like Coroutine in Unity
I required to use multiple coroutines as per my game requirements but I found that its performance hungry. So I decided to write something own using Update method that behave similar to Coroutine in Unity. I can say its TimeManager class for implementation.
Main requirement, at a time I can run multiple instances of this TimeManager class because at many placed within the environment time based activities are running.
In this please give me, just an idea about kind of implementation remains good for me. I will do the code and share for other developers to use.
Tell us more. What exactly do you want this system to do? If it is in some way trying to achieve something that Coroutines could, but more efficiently, what makes you think you can do that?
And how many coroutines are you talking about? Personally I suspect that your issues are more likely to be do with how much you're trying to do (each frame) in those coroutines, than with how many of them there are.
In short, probably not worth bothering with this.
Yes, I want to create something like coroutine - that wait for specific amount of time and after that call specific event. At a time, may be I am running with 8 to 15 coroutines currently and few of them are for longer waiting between 20 to 40 seconds.
Within performance improvement video published by Unity mentioned about this. It will always remain better if you use Update method rather than Coroutine within your game whenever you are looking for performance improvement.
Ok. You have 8-15 coroutines that are just waiting? I don't believe that's the cause of your performance issues. What you're proposing sounds like a waste of time to me. But it'd be very simple to implement.... using Coroutines (basically you'd just step through them explicitly in your Update function rather than starting them with StartCoroutine)
Answer by cdr9042 · Apr 19, 2019 at 05:00 AM
You can do that, or add a custom timer script component to each object that you want to run a timer, then add a callback to the function you want to call after the timer run out
If you want to use TimeManager, you can try this
public class FunctionCountdown
{
public float timeLeft;
public Action functionCall;
public FunctionCountdown(Action functionCall, float timeLeft)
{
this.timeLeft = timeLeft;
this.functionCall = functionCall;
}
public void OnUpdate()
{
timeLeft -= Time.deltaTime;
if (timeLeft <= 0f)
{
functionCall();
}
}
}
//class TimeManager:
List<FunctionCountdown> functionList;
public void AddFunction(Action func, float time) //call this to add function and time to the list
{
functionList.Add(new FunctionCountdown(func, time));
}
private void Update()
{
foreach (var item in functionList)
{
item.OnUpdate();
}
}
How does this improve upon what you can already do with the Invoke
function?
Oh, and you'll probably want to be removing entries from your list at some point :)