Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

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

Discussion in 'Scripting' started by anthonov, May 5, 2023.

  1. anthonov

    anthonov

    Joined:
    Sep 24, 2015
    Posts:
    160
    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 ?
     
  2. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    4,394
    You can simply cache a WaitForSeconds in the script
     
  3. anthonov

    anthonov

    Joined:
    Sep 24, 2015
    Posts:
    160
    I can't cache them in my case, their length change all the time.
     
  4. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    4,394
    Maybe switch over to async c# methods instead?
     
  5. anthonov

    anthonov

    Joined:
    Sep 24, 2015
    Posts:
    160
    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.
     
  6. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,043
    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.
     
    DevDunk and MaskedMouse like this.
  7. anthonov

    anthonov

    Joined:
    Sep 24, 2015
    Posts:
    160
    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.
     
  8. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,525
  9. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,525
    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.
     
    orionsyndrome likes this.