StartCoroutine doesn't wait for next StartCoroutine
Hi,
I followed a tutorial on how to make a guy switch weapons and implemented 2 StartCoroutine one after another. The point is to first make a character hide his active gun A and take out his second gun B. What I have now is that it just goes directly to gun B without waiting for gun A animation to finish. The code looks pretty accurate to me. If I insert a 1 seconds delay between switching animations it works as exacted, but that is not how you code :D
My code:
IEnumerator SwitchWeapon(int holsterIndex, int activateIndex) {
yield return StartCoroutine(HolsterWeapon(holsterIndex));
yield return StartCoroutine(ActivateWeapon(activateIndex));
activeWeaponIndex = activateIndex;
}
IEnumerator HolsterWeapon(int index) {
var weapon = GetWeapon(index);
if (weapon) {
rigController.SetBool("holster_weapon", true);
while (rigController.GetCurrentAnimatorStateInfo(0).normalizedTime < 1.0f) {
yield return new WaitForEndOfFrame();
}
}
}
IEnumerator ActivateWeapon(int index) {
var weapon = GetWeapon(index);
if (weapon) {
rigController.SetBool("holster_weapon", false);
rigController.Play("equip_" + weapon.weaponName);
while (rigController.GetCurrentAnimatorStateInfo(0).normalizedTime < 1.0f) {
yield return new WaitForEndOfFrame();
}
}
}
Tutorial: https://youtu.be/HZuazvqaYkU?t=1130
My animation setup:
I call a equip animation by code and holster animation gets triggered by the bool property changed
Answer by ShvetsJR · Jul 14, 2020 at 11:06 AM
One solution that seems to work correctly is:
IEnumerator HolsterWeapon(int index) {
var weapon = GetWeapon(index);
if (weapon) {
rigController.SetBool("holster_weapon", true);
yield return new WaitForSeconds(rigController.GetCurrentAnimatorStateInfo(0).length);
}
}
But I am not sure its a good approach... Can someone validate it?