0
\$\begingroup\$

I am making a small FPS in unity 5. I made a cursor animation that I want to play only for a brief moment. I tried to do this using some code:

using System.Collections;

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

public class CrossAnimate : MonoBehaviour {

public GameObject UpCurs;
public GameObject DownCurs;
public GameObject LeftCurs;
public GameObject RightCurs;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.GetMouseButtonDown(0))
    {
        UpCurs.GetComponent<Animator>().enabled = true;
        DownCurs.GetComponent<Animator>().enabled = true;
        LeftCurs.GetComponent<Animator>().enabled = true;
        RightCurs.GetComponent<Animator>().enabled = true;
        WaitingAnim();
    }
}

IEnumerator WaitingAnim()
{
    yield return new WaitForSeconds(0.1f);

    UpCurs.GetComponent<Animator>().enabled = false;
    DownCurs.GetComponent<Animator>().enabled = false;
    LeftCurs.GetComponent<Animator>().enabled = false;
    RightCurs.GetComponent<Animator>().enabled = false;
}

}

All of the four animators on the four gameobjects (UpCurs, DownCurs, etc) are not enabled by default. When clicking the mousebutton they should be enabled so it plays the animation and then after a brief time, they should disable again. The problem is that they don't disable.

Any help would be appreciated!

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You call a Coroutine by using StartCoroutine("method name"). Calling it like this probably does not trigger the yield and thus nothing happens so your code should look like :

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

    public class CrossAnimate : MonoBehaviour {

    public GameObject UpCurs; public GameObject DownCurs; public GameObject LeftCurs; public GameObject RightCurs;

    // Use this for initialization void Start () {

    }

    // Update is called once per frame void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            UpCurs.GetComponent<Animator>().enabled = true;
            DownCurs.GetComponent<Animator>().enabled = true;
            LeftCurs.GetComponent<Animator>().enabled = true;
            RightCurs.GetComponent<Animator>().enabled = true;
            StartCoroutine(WaitingAnim());
        } }

    IEnumerator WaitingAnim() {
        yield return new WaitForSeconds(0.1f);

        UpCurs.GetComponent<Animator>().enabled = false;
        DownCurs.GetComponent<Animator>().enabled = false;
        LeftCurs.GetComponent<Animator>().enabled = false;
        RightCurs.GetComponent<Animator>().enabled = false; 
} 
}
\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .