Kevin Cranfield
Kevin Cranfield

Reputation: 51

Code not starting/stopping animation

Logically this code looks fine to me but is not working as intended when i run the code the animation does not activate or deactivate. I put the qwerty int in there for testing purposes.

void WaitingForPipe () {

    qwerty = 1;
    PipeEntry.GetComponent <Animator>().enabled=true;

    Wait ();

    qwerty = 2;
    //yield return new WaitForSeconds(2);

    PipeEntry.GetComponent<Animator>().enabled=false;
    qwerty = 3;
    //GameObject.Find("FPSController").GetComponent("FirstPersonController").enabled=true;
}

IEnumerator Wait()
{
    //This is a coroutine
    //Debug.Log("Start Wait() function. The time is: "+Time.time);
    //Debug.Log( "Float duration = "+duration);
    yield return new WaitForSeconds(2);   //Wait
    //Debug.Log("End Wait() function and the time is: "+Time.time);
} 

Upvotes: 1

Views: 313

Answers (2)

Programmer
Programmer

Reputation: 125275

It looks like you want to wait 2 seconds before running Wait ();. If that's true then you must yield your your Wait (); function.

Change

Wait ();

to

yield return Wait();

and you must change your WaitingForPipe function to a coroutine function too so that you can yield inside it. void WaitingForPipe () should be IEnumerator WaitingForPipe ()


Code not starting/stopping animation

There is no code in your question that is starting or stopping the animation, you do not and should not have to enable/disable the Animator in order to play or stop it. That's wrong. Remove your PipeEntry.GetComponent <Animator>().enabled=true/false code.

This the proper way to play/stop animation:

Play:

string stateName = "Run";
Animator anim = GetComponent<Animator>();
anim.Play(stateName);

Stop:

anim.StopPlayback();

Upvotes: 1

Filip Vondr&#225;šek
Filip Vondr&#225;šek

Reputation: 1208

Coroutines in C# aren't methods that you run by just calling them, that only works in UnityScript. In order to start a Coroutine in C#, you must call StartCoroutine(YourCoroutine()); on a MonoBehaviour instance.

Your code would work if it looked like this:

IEnumerator WaitingForPipe()
{
    PipeEntry.GetComponent <Animator>().enabled=true;

    yield return new WaitForSeconds(2);

    PipeEntry.GetComponent<Animator>().enabled=false;
}

and you have to start the Coroutine by using StartCoroutine(WaitingForPipe()); from somewhere.

You can read more about Coroutines here in the official documentation: https://docs.unity3d.com/Manual/Coroutines.html

Upvotes: 2

Related Questions