1

So i have tried doing this :

void Update()
    {
        if (isWalkingTowards)
        {
            if (Vector3.Distance(character.transform.position,this.transform.position)<0.7)
            {
                **StartCoroutine(Example());**
                Instantiate(character, new Vector3(-6, 0, -1), Quaternion.identity);
                Destroy(character);

            }
        }
    }
    **IEnumerator Example()
    {
        yield return new WaitForSecondsRealtime(5);
        Debug.Log("This function should be read before it is instantiated or destroyed");
    }**

But it just instantiates and destroys object and after that it shows me that message!

Enes Zeqiri
  • 55
  • 1
  • 7
  • 3
    Not sure I understand. Why don't you put `Instantiate` and `Destroy` calls inside `Example`, after the `yield return new WaitForSecondsRealtime(5);` – Ruzihm Mar 25 '21 at 20:53
  • Well done on getting a solution - I don't know if anyone mentioned the reason to move the `Destroy` call inside the `IEnumerator`. The reason is because once the `IEnumerator` is called, the next line of code doesn't wait for it to execute before continuing. The delay happens within the `IEnumerator` function, dictated by the yield return statement you have. So you were destroying the object outside your delay. – impo Mar 25 '21 at 23:45

2 Answers2

2

I should have done this:

void Update()
    {
        if (isWalkingTowards)
        {
            if (Vector3.Distance(character.transform.position,this.transform.position)<0.7)
            {
                **StartCoroutine(Example());**
            }
        }
    }
    **IEnumerator Example()
    {
        yield return new WaitForSecondsRealtime(5);
        Debug.Log("This function should be read before it is instantiated or destroyed");
        Instantiate(character, new Vector3(-6, 0, -1), Quaternion.identity);
        Destroy(character);
    }**
Enes Zeqiri
  • 55
  • 1
  • 7
0

Here is a super helpful link on a bunch of ways to wait in unity: How to make the script wait/sleep in a simple way in unity

Also, I think the issue you're currently running into is that the code won't wait for StartCoroutine(Exmaple()) to finish. You have to put the code you want to execute before and after in Example.

Simonster
  • 593
  • 4
  • 10