0

I tried to use delegate chain like below, trying to make animation in unity:

public class Class1
{
    class Dele {

        delegate void MyDelegate();
        private MyDelegate dele;

        private int count = 0;

        public void Animate() {
            dele = new MyDelegate(DoIe);
        }

        IEnumerator Ie() {
            Debug.Log(count);
            count += 1;
            yield return new WaitForSeconds(5f);
        }

        private void DoIe() {
            StartCouroutine(Ie());
            for (int i=0; i<10; i++) {
                dele += DoIe;
            }

            dele();
        }
    }

    //call new Dele().Animate() here
}

I thought the Log will go like 1 (5 secs) 2 (5 secs) ... 10

but instead, 1 2 .. 10 was logged at the same time.

If I want to callback another Ie after 5 second, what should I do??

tink
  • 39
  • 1
  • 6
  • Possible duplicate of [Wait for a coroutine to finish before moving on with the function C# Unity](https://stackoverflow.com/questions/44359236/wait-for-a-coroutine-to-finish-before-moving-on-with-the-function-c-sharp-unity) – Draco18s no longer trusts SE Jul 18 '18 at 14:40

2 Answers2

1

With coroutines it's the code inside the routine (the IEnumerator method) that runs later. The code after StartCoroutine() in your void-returning method above will run synchronously (straight away), like you saw.

You don't need a delegate here at all. All you need is this:

IEnumerator Ie() {
    for (int i=0; i<10; i++) {
        Debug.Log(count);
        count += 1;
        yield return new WaitForSeconds(5f);
    }
}

private void DoIe() {
    StartCoroutine(Ie());
}
David Oliver
  • 2,251
  • 12
  • 12
0

First of all, your class needs to inherit from MonoBehavious for StartCoroutine to work. Then in regards of your question: you need to start the coroutine with a delay, just adding them to a multicast delegate is simply not doing what you think you are

zambari
  • 4,797
  • 1
  • 12
  • 22