Can't figure out how to start a saved Coroutine variable

45 Views Asked by At

My AI units have a few coroutines for different tasks, I wanted to be able to store the last used coroutine so that they can "pause" and "continue", but ran into a trouble that I couldn't figure out.

So I give the unit an order MoveToResourceStart(), saving the MoveToResource() as lastCoroutine and starting it. Then I trigger StopAlly(), stopping agents path and making it look at player. After I try to trigger ContinueAlly() to resume the last coroutine, it throws me an error: "Coroutine 'lastCoroutine' coudln't be started!"

Stripped Code:

Coroutine lastCoroutine = null;

    protected void StopAlly(Transform player)
    {
        if (lastCoroutine != null)
           { 
              StopCoroutine(lastCoroutine); 
              agent.ResetPath();
           }
        this.transform.LookAt(player.position);
    }
    protected void ContinueAlly()
    {
       if (lastCoroutine != null) StartCoroutine("lastCoroutine");
    } 

    protected void MoveToResourceStart()
    {
        if (lastCoroutine != null) StopCoroutine(lastCoroutine);
        lastCoroutine = StartCoroutine(MoveToResource());
    }

    protected IEnumerator MoveToResource()
    { 
        agent.SetDestination(resource.gameObject.transform.position);
        //and a bunch of movement related code, works fine
    }

I can't figure out what I'm doing wrong, or if I'm trying to approach the subject completely wrong. Anyone knows how I could start the "lastCoroutine"? I couldn't find a solution by googling.

1

There are 1 best solutions below

1
iimuli On

EDIT AND SOLUTION:-----------------------------------------------------

a friend of mine helped me out, so the problem was trying to recall the coroutine with the string.

I changed:

Coroutine lastCoroutine = null;

to :

private IEnumerator lastCoroutine = null;

I can store it with lastCoroutine = MoveToResource(); and I can simply restart it with "StartCoroutine(lastCoroutine);"

Hopefully this helps our fellow developers

Side mention: On my code example lastCoroutine = StartCoroutine(MoveToResource()); started the coroutine, as someone pointed that I stripped it too much.