pros / cons using custom struct IEnumerator instead of WaitForSeconde()

At one point in my game I have a lot of coroutines running. Garbage Collector work a lot and make frames freeze because a lot of instance of WaitForSeconds are created and then deleted by GC.

So why not simply replace all these WaitForSeconds() classe by a Struct custom one ? So that yield return a stack value instead of a heap managed item ?

You can simply cache a WaitForSeconds in the script

I can’t cache them in my case, their length change all the time.

Maybe switch over to async c# methods instead?

I never needed this for now, so I will have to learn and then replace all, but for now that I need a quick fix for all my coroutines if possible, I’m looking for the simpliest solution like just switching to struct version if that does not come with bad surprise.

Why not simply stop having so many coroutines ffs. They are not omnipotent, there are many limitations and problems associated with them. Garbage for example. Make you own time-based event system, poof, no garbage.

2 Likes

I’m certainly going to do that, but for this time, I just want to know if it is ok to make a quick fix by you know what.
I did a quick test, it looks ok, and I want to know if there is a good reason that it was class instance in the first place.

If you need a garbage free WaitForSeconds , have a look at my solution :slight_smile:

Note that a struct does not help at all. The IEnumerator yield value is always an object. So yielding a struct means the struct will be boxed on the heap and thus generating garbage.

1 Like