- Home /
STOPPING an animation after X seconds C# ,how ??
how do i stop an animation which has been set to play on a character after x amount of seconds ? could this be done with some sort of countdown timer , if so how would i go about writing one ?
thank you very much .
smithy = GameObject.Find("smithy"); this script is attached to my character "smithy"
if (number == 4) // "Number" is just a variable
{ //this moves the character forward while playing the walking animation
smithy.transform.position += smithy.transform.forward * 5.0f * Time.deltaTime;
smithy.animation.Play("Walking");
// this is where the character "Smithy" should only be walking for 4 seconds then essentially the script should stop after 4 seconds. "Number"
// here is where the forward movement should also be stopped after 4 seconds "Number"
}
Answer by Caliber Mengsk · Aug 24, 2012 at 07:26 PM
GameObject.Find is not needed for the object the script is attached to. It's a slow command (as it looks through every game object in the scene to see if it's name is the string given) You can simply use gameObject in place of anywhere smithy is called or in the case of transform, you don't even need gameObject as it supposes you mean the current game object. This will help a bit in optimization.
You just need a timer to check with. Here is how I would do it.
var number:float = 4; //length of time to run
var startTime:float = 0;
private var wasRun:boolean = false;
function Start()
{
startTime = Time.realtimeSinceStartup;
}
function Update()
{
if(Time.realtimeSinceStartup <= startTime + number)
{
transform.position += transform.forward * 5.0f * Time.deltaTime;
animation.Play("Walking");
}else{
if(!wasRun)
{
animation.Stop();
wasRun = true;
}
}
}
public function ResetTimer()
{
startTime = Time.realtimeSinceStartup;
wasRun = false;
}
Now, with this script, you can even call ResetTimer to do it over and over again. It needs to have the wasRun check, otherwise it would always be run every frame, stopping you from playing any animations after this event. Hope this helps.
Answer by Lemo Dev · Aug 24, 2012 at 07:05 PM
Try this
void Update()
{
if (number == 4)
{
smithy.transform.position += smithy.transform.forward * 5.0f * Time.deltaTime;
smithy.animation.Play("Walking");
StartCoroutine("StopAnimation");
}
}
IEnumerator StopAnimation()
{
yield return new WaitForSeconds(5);
smithy.animation.Stop();
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Two methods are called on repet in my code and I don't know why 1 Answer
Object follows mouse onclick 0 Answers
Flip over an object (smooth transition) 3 Answers