- Home /
How to call a coroutine before an animation? (JS or C#)
Hi there,
I've been having issues with calling coroutines since I started coding. I'm sort of picking scripting up as I go, but this is something that I simply can't make sense of, and there's no clear examples on how to use it in my situation.
What I'm trying to do:
function Update (); {
if (Input.GetKey (KeyCode.Space))
{
//Wait for .5 seconds so that the model has time to wind up before he
//actually jumps
WaitForSeconds(.5);
animation.CrossFade("jump");
}
}
From the documentation I'm reading, I have to start a coroutine so that I can call it, but I can't use it inside the update function, so I have to create a whole new function just for my one animation? That makes no sense, but if that's the easiest way to wait half a second, can someone show me the proper formatting to do so?
Answer by fafase · Apr 02, 2014 at 07:35 PM
So you want to call the coroutine to make the animation starts later. You cannot run a coroutine from Update because it cannot be yielded.
var waitForJump : boolean = false;
function Update (){
if (Input.GetKey (KeyCode.Space) && !waitforJump)
{
waitForJump = true;
Jump();
}
}
function Jump(){
var timer:float = 0f;
while(timer < 0.5f){
timer += Time.deltaTime;
yield;
}
animation.CrossFade("jump");
waitForJump = false;
}
the boolean makes sure you cannot call the coroutine many time in a row.
This code returns the error: (13,11): UCE0001: ';' expected. Insert a semicolon at the end.
Do I need to be defining the timer up in variables?
Thanks for the help! I feel I'm getting closer to understanding it finally.
Oh I think I am mixing C# and Js. The timer declaration is wrong.
float timer; -> var timer :float;
I edit the answer.
Answer by Ben-Stoneman · Apr 02, 2014 at 03:59 PM
Try this:
C#:
void Update()
{
if (Input.GetKey (KeyCode.Space))
{
StartCoroutine(Wait());
animation.CrossFade("jump");
}
}
IEnumerator Wait()
{
yield return new WaitForSeconds(5);
}
http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.StartCoroutine.html
This didn't work unfortunately :/ Put it in a script all by itself and attached to player to make sure.
Your answer
![](https://koobas.hobune.stream/wayback/20220613141756im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Move animation in coroutine problem 0 Answers
Passing reference of transform properties to coroutine animation? 1 Answer
Lerp in Nested Coroutines doesn't work if I add some functions inside the Coroutines 1 Answer
My Coroutine does not get called 4 Answers
Animation Curve or Coroutine? Performance question. 1 Answer