0

I am making a Unity sword game. I have it so when you click Mouse0 it plays an animation and changes attacking to True. I am trying to make it so after two seconds(Or after the animation switches to Idle) it changes attacking to False. The code I have makes Unity stop responding.

EDIT: I know the code is in an infinite loop, but I need it so when ever I click mouse0 it works, not just at the beginning of testing. Is there a fix/ better way to do this

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

public class SwordSwing : MonoBehaviour
{
    Animator anim;
    public static bool attack = false;
    private bool a = true;

    void Start()
    {
        StartCoroutine(waiter());
        anim = gameObject.GetComponent<Animator>();
    }

        IEnumerator waiter()
        {
            while(a = true)
                if (Input.GetMouseButtonDown(0))
                {
                    Debug.Log("True");
                    attack = true;
                    anim.SetTrigger("Active");
                    anim.SetTrigger("Idle");
                    yield return new WaitForSeconds(2);
                    attack = false;
                    Debug.Log("False");
                }



        }

}
InedHelp
  • 17
  • 3
  • If the user doesn't click the mouse button, the coroutine needs to yield control (e.g. with `yield return null` somewhere inside your while loop). See [this article](https://answers.unity.com/questions/904427/waiting-for-a-mouse-click-in-a-coroutine.html). – John Wu Jan 11 '20 at 00:21
  • 1
    `while(a = true)` is assignment, not comparison. As such this loop will never end. It will also never end because `a` is not modified inside the loop. The assignment of `anim` should happen before you start the coroutine, not after. – Retired Ninja Jan 11 '20 at 00:21
  • 2
    unity stops working because the while loop is infinite, remove it. If you want to wait for realtime seconds. ``yield return new WaitForSeconds(2f); attack = false; `` . For frame delay (you can put it inside a loop to wait for more frames) ``yield return null;`` I'm pretty sure this is a duplicate –  Jan 11 '20 at 00:24
  • 3
    Does this answer your question? [How make the script wait/sleep in a simple way in unity](https://stackoverflow.com/questions/30056471/how-make-the-script-wait-sleep-in-a-simple-way-in-unity) –  Jan 11 '20 at 00:31

1 Answers1

0

Add a yield return null; at the end of your while so it can returns from the Coroutine and finish the frame.

Also, replace your while condition by while(a == true) (with double =) or just while(a):

while(a == true) {
  if (Input.GetMouseButtonDown(0)){
    Debug.Log("True");
    attack = true;
    anim.SetTrigger("Active");
    anim.SetTrigger("Idle");
    yield return new WaitForSeconds(2);
    attack = false;
    Debug.Log("False");
  }
    yield return null;
}
Maarti
  • 3,600
  • 4
  • 17
  • 34