how to play this animation for 10sec or 20sec after collision
using UnityEngine;
using System.Collections;
public class anis : MonoBehaviour {
// Use this for initialization
void Start () {
}
void Update()
{
//animation.Play("Barking");
}
void OnCollisionEnter(Collision collision)
{
animation.Play("Barking");
Debug.Log("abc");
}
}
currently this animation is playing one time
i want to know how to do this for 10times
http://www.gamesgames.com/game/BlueBlox.html
This will loop the animation for the desired length of time just change animLength
private float endTime; // End time of animation
private float animLength = 20.0f; // Desired length in seconds for animation to be played
void Start() {
animation.wrapMode = WrapMode.Loop // Makes sure the animation will loop
}
void OnCollisionEnter(Collision collision) {
endTime = Time.time + animLength; // Gets the time for the animation to end
animation.Play("Barking"); // Plays the animation
while (Time.time != endTime + 1) // While the timer is active
if (Time.time == endTime) { // If time is up
animation.Stop(); // Stops the animation
animation.Play("Idle"); // Resets the animation to the idle animation
break;
}
}
}
Wouldn’t using a loop for that just freeze or crash the game? I was under the impression that you would need to use a yield statement for having a script pause.
OP: I would look into how to use yield statements.
Here is a simple rewrite of what you had, using a bit more variables and control over the animation. You never really want to just say “Play”, usually you will “CrossFade” clips. This gives a smoother appeal to your work.
using UnityEngine;
using System.Collections;
public class GravityObject : MonoBehaviour {
public string idleName = "Idle";
public string barkingName = "Barking";
string current;
// Use this for initialization
void Start () {
Play(idleName);
}
void Update(){
}
void OnCollisionEnter(Collision collision){
StartCoroutine(Bark(10));
}
IEnumerator Bark(float duration){
CrossFade(barkingName);
yield return new WaitForSeconds(duration);
if(current == barkingName) CrossFade("Idle");
}
void Play(string name){
current = name;
animation.Play(name);
}
void CrossFade(string name){
current = name;
animation.CrossFade(name);
}
}
I specifically used methods to do the crossfading and playing so that I can also keep reference on the current animation playing. In logic, you would do this so that if your animation changed during the course of the wait for the barking to finish, ten it wouldnt swap to idle for no reason, it would just leave it alone.