0
\$\begingroup\$

I've read up on several ways of doing this but can't seem to find one that works for what I need. I have a method that is called and performs some logic, and then I need it to wait for a period of time, then continue with more logic in the same function. I had planned on using a coroutine which is what I did with another part of the game, but I'm running into an issue because the class doesn't directly inherit from Monobehaviour so it can't start a coroutine. I've tried Thread.sleep, but that just makes the game stop, so that isn't what I want. I don't know if there is some way to put a timer in there that will wait and then continue the function or if there is something else that I'm overlooking.

Here is the current code:

public void AssaultRifleShot (GameObject mainBall)
{
    if (AmmoRemaining > 0) 
    { 
        //if there is ammo remaining, set the main ball to just a normal ball so it can be destroyed on impact and then start coroutine
        mainBall.GetComponent<Ball> ().mainBall = false;
        mainBall.GetComponent<Ball> ().onBallHitPaddle -= AssaultRifleShot; //unsubscribe to event when mainBall is set to false.
        StartCoroutine(timer, coroutineHost);

        AmmoRemaining -= 1;
    } 
    else 
    {
        DestroyPickUp();    
    }
}

There are other method calls inside the code for the coroutine, so those would end up going after whatever timer or someting goes in instead of the coroutine.

\$\endgroup\$
  • 1
    \$\begingroup\$ It looks like you are on the right track already with this “coroutineHost”, which I assume is a MonoBehaviour that runs coroutines arbitrarily. Is this not functioning? \$\endgroup\$ – Ed Marty Jul 8 '18 at 12:39
  • \$\begingroup\$ The problem is that I have to pass it in. If I follow it all the way back through the function calls, I have to pass it into OnCollisionEnter2d, which can't take that as a parameter. I don't know of any other way to pass it in. Can I make an instance of Monobehaviour? I feel like that wouldn't work. \$\endgroup\$ – ethan codes Jul 8 '18 at 16:04
  • 1
    \$\begingroup\$ Any MonoBehaviour should work. At some point you have a MonoBehaviour in the call stack which you should be able to use. Otherwise you can just have a singleton MonoBehaviour made for this purpose. \$\endgroup\$ – Ed Marty Jul 8 '18 at 16:11
  • \$\begingroup\$ Oooh I see. I didn't realize that. Sounds like I have a fix then! I'll try it out tonight. Thanks! \$\endgroup\$ – ethan codes Jul 8 '18 at 16:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.