Starting Coroutine Doesnt Work Properly

So if i start coroutine from different script, it stops at yield return xxxxx code line. it doesnt go below. I didnt understand at first but after i create a another function(in the IEnumerator script) and started coroutine in there. I called that function from my other script and it worked.

so i thought its a bug maybe?

for the people who suffered from my english ;

[Script x]
StartCoroutine(y.SetWeaponSpeed(speed, seconds));

[Script y]
    public IEnumerator SetWeaponSpeed(int speed, float seconds)
    {
        shootSpeedMultiplier = speed;
        Debug.Log("hit here");
        yield return new WaitForSeconds(seconds);
        Debug.Log("Doesnt hit here");
        shootSpeedMultiplier = 1;
    }

this doesnt work

[Script x]
y.HandleWeaponSpeed(speed, seconds);



[Script y]

public void HandleWeaponSpeed(int speed, float seconds)
    {
        StartCoroutine(SetWeaponSpeed(speed, seconds));
    }

    public IEnumerator SetWeaponSpeed(int speed, float seconds)
    {
        shootSpeedMultiplier = speed;
        yield return new WaitForSeconds(seconds);
        shootSpeedMultiplier = 1;
    }

this is working.

Your English isn’t the problem. Use the code tags to format your code.

9841839--1416087--code-tag.png

If you StartCoroutine( someComponent.someMethod() ), then the GameObject that has someComponent needs to exist and be active the whole time, or the routine won’t continue to run.

The GameObject that i started coroutine is the only object that destroyed others are working. So is this the problem? The gameobject that i started coroutine should be not destroyed too ?

Akshually… :slight_smile: No.

The GameObject where this StartCoroutine() comes from is who hosts and runs the coro, not where the coro “came from.”

Remember, IEnumerators don’t even have to be on any GameObject at all to be created and then handed to good old StartCoroutine().

As for OP… for your second code snippet, be sure the reference you have to y is NOT the prefab… It has to be a real live breathing GameObject Instantiated in your hierarchy capable of hosting that coroutine.

1 Like

Yep, rule of thumb: only StartCoroutine methods that are within the current script, never StartCoroutine on external components. It only takes an additional indirect method call to adhere to this rule and it’s well worth applying that discipline.

So instead of:

StartCoroutine(otherScript.TheRoutine());

Prefer to always do this:

otherScript.StartTheRoutine();

private void StartTheRoutine()
{
    StartCoroutine(TheRoutine());
}
1 Like