Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

I have 2 different animations for attack.

Discussion in 'Scripting' started by Raffalius, Feb 21, 2020.

  1. Raffalius

    Raffalius

    Joined:
    Sep 11, 2019
    Posts:
    4
    if (Input.GetMouseButton(0))
    {
    StartCoroutine(Attack());
    }
    else if (crouch == true)
    {

    StartCoroutine(CrouchAttack());
    }



    New
    How do i cancel Attack when crouch == true?
    and launch CrouchAttack instead :)
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,590
    Hello and welcome!
    You can save the created Coroutine using an 'IEnumerator coroutine' type. You can then stop a Coroutine by calling StopCoroutine(coroutine). You may additionally want to reset your animation to a default state or something, but that's up to your game design. I would recommend taking a closer look at these examples if you want to stop Coroutines:
    https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html

    I'm personally not a big fan of Coroutines. Instead i would construct a small class to deal with the animation states (offering functions for Start(), IsFinished(), Reset(), ProgressByTime(float deltaTime) and so on to make my life easy), and then handle the flow of the combat / gameloop using a statemachine. Statemachines basically define what can happen in each state, what actions can be taken from there and what others states you enter following these actions. They can easily be drawn, and once you've done that, can normally be easily implemented as well. An example would look like this:

    So in your case, you would have a state for "Standing", from which you can enter "Crouching". When in Crouching you can either crouch-attack or stand up. When standing you can start walking, when walking you can start running and so on. This helps you keep track of what can or cannot be done in each state. When implementing it, you'd normally create methods for "Standing()", "Crouching()" and so on, and conditionally call them in nested if-statements. If one thing you can do in the Standing-state is jumping, then you'd check for jumping inputs being pressed there, and if detected, set the state to "Jumping", which will be entered next frame (or directly afterwards, depending on how you implement it).
     
  3. Raffalius

    Raffalius

    Joined:
    Sep 11, 2019
    Posts:
    4
    Wow, you really went the extra mile here :)
    Thanks a lot for responding, this solved my problem :)
    Will definitely try out your method.