- Home /
wait until an animation finishes
Hello Unity3D i have a question about animation.How can i make it that when i do an animation you can't do anything else until animation is finished?For example,when i make my character throw a projectile the idle animation that plays waits for it to finish but when i click the movement keys like up,down,left,right the character still moves.How can i make it that the character plays an animation and you can't do nothing to stop it until the animation is completely finished?
Answer by zharik86 · Oct 15, 2014 at 06:08 AM
Use coroutine and bool variable. Idle and Walk animation is loop(write on CSharp):
private bool state = false;
private bool change = false;
private string curAnim = "";
void Update() {
//play idle
if (Input.GetKeyDown(KeyCode.I)) {
if(curAnim != "Idle") {
curAnim = "Idle";
change = true;
}
}
if (Input.GetKeyDown(KeyCode.T)) {
if(curAnim != "Walk") {
curAnim = "Walk";
change = true;
}
}
if(change && !state) {
this.animation.Play(curAnim);
this.StartCoroutine(this.myPlay(curAnim));
}
}
public IEnumerator myPlay(string tpAnim) {
curAnim = tpAnim;
while(!change) {
state = true;
yield return new WaitForSeconds(this.animation.clip.length);
state = false;
}
}
I hope that it will help you.
Thanks for the script ill convert it to javascript right now.
@tokenten Write your comment as comment, not answer. For comment, press button "Add new comment" below answer. If you need help to transfer in Java, just write here.
And if I or everybody help you, than mark rigth answer.
Oh sorry i haven't been here in a while so i kind of forgot...Also you can help me with writing the script in java?
@tokenten I transfer my script in Java. And I hope that it will help you further most to transfer one program$$anonymous$$g language to another. As the transfer in other program$$anonymous$$g language not such rare task:
private var state: boolean = false;
private var change: boolean = false;
private var curAnim: String = "";
function Update() {
//play idle
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.I)) {
if(curAnim != "Idle") {
curAnim = "Idle";
change = true;
}
}
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.T)) {
if(curAnim != "Walk") {
curAnim = "Walk";
change = true;
}
}
if(change && !state) {
this.animation.Play(curAnim);
this.StartCoroutine(this.myPlay(curAnim));
}
}
function myPlay(string tpAnim) {
curAnim = tpAnim;
while(!change) {
state = true;
yield WaitForSeconds(this.animation.clip.length);
state = false;
}
}
That's all. I hope that works.