0
\$\begingroup\$

I have a class like so:

public class SomeObject : MonoBehaviour
{
    protected List<EdibleStuff> SomeItemsToConsume;

    private void StartConsuming()
    {
        this.SomeItemsToConsume
            .ForEach(item =>
            {
                StartCoroutine(Consume(item));
            });
    }

    private IEnumerator Consume(EdibleStuff edibleStuff)
    {
        yield return new WaitForSecondsRealtime(2);

        // Check whether edibleStuff is still fresh after 2 seconds
        // Figure out how to consume it -- e.g. by cooking, eating raw, whatever
    }
}

Before SomeObject consumes the next item in the SomeItemsToConsume list, I would like it to wait another short period of time, say, another 2 seconds.

I have tried these approches:

  1. I added another yield return new WaitForSecondsRealtime(2); statement at the end of the Consume(EdibleStuff edibleStuff) method, but that did not work.
  2. I added another co-routine, which simply contains the statement yield return new WaitForSecondsRealtime(2); in its definition, at the end of the ForEach loop, but that did not work either.

How can I achieve the effect I want?

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

You could put the ForEach inside the coroutine:

public class SomeObject : MonoBehaviour
{
    protected List<EdibleStuff> SomeItemsToConsume;

    private IEnumerator Consume()
    {
        this.SomeItemsToConsume
        .ForEach(item =>
        {
            WaitForSecondsRealtime wait = new WaitForSecondsRealtime(2);

            /// Process your item...

            yield return wait; 
        });
    }
}

Since what it was done in your StartConsuming method was that in your loop a 'n' number of coroutines (being 'n' the count of your list) were being started at the same frame. Having it inside a coroutine makes sure that the List moves to the next element once the WaitForSecondsRealTime's keepWaiting property returns true, which is not on the same frame (even if the time passed were 0).

Hope it helps.

\$\endgroup\$
1
  • \$\begingroup\$ Thank you for your reply! Unfortunately, I do not have access to my repository until next week. Once I verify that your answer works, I will mark it as accepted. \$\endgroup\$
    – user112729
    Apr 26, 2018 at 17:48

You must log in to answer this question.