Two coroutines from different scripts conflicting, causing animation and input issues

So, I’m making sort of a 90s-era Resident Evil-inspired game. I have a script for tank controls, and another script for shooting mechanics. I have a monster character who currently runs on three scripts: one for AI pathfinding to the player, one for death and health, and another for attacking the player.

Currently, in order for the character to fight monsters in the game, they have to hold down the right mouse button, then left click to shoot their gun, without moving out of place (like in the classic style). Everything works beautifully, the monster dies, its AI is good, the shooting works, but the big issue comes when the monster actually attacks the player.

Two animations play when the player is attacked–one animation on the player getting attacked, and the monster attacking, and both run out of the monster attacking script. This works perfectly fine when the player is not aiming their gun or shooting, but when they are aiming and shooting, it causes all sorts of problems. If the player is aiming at the monster when the monster attacks, when the animation of them getting attacked is over, the player can’t move unless they right click to aim again. And if the enemy attacks the player while in the middle of a shooting animation, then the animation of the player getting attacked doesn’t play at all, and they’re stuck in the “aiming” animation.

I know all this is very vague, so I posted a gif of what happens if the “monster attack” script activates in the middle of the shooting script’s shooting Coroutine. If anyone has any idea how to fix this problem, it would be greatly appreciated, because I’ve been tearing my hair out for two days trying to fix it.

Codes:

Code for the “monster attacking” script.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class VampireBite : MonoBehaviour
{

    public GameObject vampire;
    public GameObject Raquel;
    public GameObject bloodSquirt;
    public GameObject biteTrigger;
    public AudioSource biteSound;
    public AudioSource raquelGrunt;

    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Player")
        {
          
            StartCoroutine (VampireBiteRaquel());
        }
    }

    IEnumerator VampireBiteRaquel()
    {
        vampire.GetComponent<UnityEngine.AI.NavMeshAgent>().enabled = false;
        Raquel.GetComponent<TankControls>().enabled = false;
        Raquel.GetComponent<WeaponMechanics>().enabled = false;
        raquelGrunt.Play();
        vampire.GetComponent<Animator>().Play("Bite");
        Raquel.GetComponent<Animator>().Play("GetBitten");
        biteSound.Play();
        yield return new WaitForSeconds (1f);
        bloodSquirt.SetActive(true);
        yield return new WaitForSeconds (0.5f);
        bloodSquirt.SetActive(false);
        yield return new WaitForSeconds (2.5f);
        vampire.GetComponent<UnityEngine.AI.NavMeshAgent>().enabled = true;
        Raquel.GetComponent<WeaponMechanics>().enabled = true;
        Raquel.GetComponent<TankControls>().enabled = true;
        vampire.GetComponent<Animator>().Play("Stalk");
    }
}

And the script for the shooting mechanics:

public class WeaponMechanics : MonoBehaviour
{
    public static bool isAiming = false;
    public GameObject thePlayer;
    public float horizontalMove;
    public AudioSource pistolShot;
    public bool isFiring = false;
    public float TargetDistance;
    public int DamageAmount = 5;


    void Update()
    {
        if (Input.GetMouseButtonDown(1))
        {
            isAiming = true;
            thePlayer.GetComponent<Animator>().Play("Aim");
            AutoAim.aimingGun = true;
        }
        if (Input.GetMouseButtonUp(1))
        {
            StartCoroutine(ReturnToTank());
            AutoAim.aimingGun = false;
            thePlayer.GetComponent<Animator>().Play("LowerGun");
        }

        if (isAiming == true)
        {
            if (Input.GetButton("Horizontal"))
            {
                horizontalMove = Input.GetAxis("Horizontal") * Time.deltaTime * 150;
                thePlayer.transform.Rotate(0, horizontalMove, 0);
            }
            if (Input.GetMouseButtonDown(0) && isFiring == false)
            {
                isFiring = true;
                StartCoroutine(FiringWeapon());
            }
        }
    }

    IEnumerator FiringWeapon()
    {
        RaycastHit Shot;
        isFiring = true;
        if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.back), out Shot))
        {
            TargetDistance = Shot.distance;
            Shot.transform.SendMessage ("DamageVampire", DamageAmount, SendMessageOptions.DontRequireReceiver);
        }
        pistolShot.Play();
        thePlayer.GetComponent<Animator>().Play("Shoot");
        yield return new WaitForSeconds(0.95f);
        thePlayer.GetComponent<Animator>().Play("AimIdle");
        isFiring = false;
    }

    IEnumerator ReturnToTank()
    {
        yield return new WaitForSeconds(0.40f);
        isAiming = false;
    }
}

8971588--1233484--bethlehem-hill-testingarea-windows-mac-linux-unity-2021315f1-personal_aHIKQaml.gif

Sounds like it is time to start debugging! Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

“When in doubt, print it out!™” - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

It sounds like you need to add code to disable aiming when the player is recovering from a hit, then resume aiming when the player has recovered.

In general, these sorts of problem are often handled by something called a finite state machine. The animator controller itself is a type of fsm, but many people like to code their own for more direct control. In this case the player getting hit would interrupt whatever state it’s currently in and go into the “hit reaction state.” In that state no input is accepted. Then, once the animation is finished, that will trigger the fsm to go back to neutral state.

1 Like