Play animation just one time in Update Function by pressing a key.

This is a part of my C# script MovePlayer.cs :

public bool regen;
public Transform Player;

    // Use this for initialization
    void Start () {
    	regen = false;
    }
    
    
    void Update () {
    	if(Input.GetAxis("Vertical") == 0){
    		Player.animation.Play("idle");
    	}
    
    	if (Input.GetKey(KeyCode.R) && Input.GetAxis("Vertical") == 0){
    		regen = true;
    	}
    		
    	if(regen){
    		Player.animation.Play("faint");
    	}
    
    // ... Rest of my script

Firstly , my script is on an empty in this empty I have my Player, I would like to start my “regen” animation but it’s like she’s freezing… I think it’s because it’s in the Update Function and it’s called on every frame so, my question is how to play the animation “regen” just one time, by pressing the “R” on my keyboard, and get back to my “idle” animation automatically?

Thanks.

Try using !Player.animation.[IsPlaying][1] to determine if an animation is playing, and if it isn't, play. You can also use GetKeyDown, since it's only called once per Key Event (only when the user presses the key). [1]: http://docs.unity3d.com/Documentation/ScriptReference/Animation.IsPlaying.html

it does not work very well.. I'll leave this function for now,thank you all!

2 Answers

2

Haven’t tested the following code but it should work.But there are some more optimized ways doing this such as using Coroutines.

 void Update () 
 {
        if(Input.GetAxis("Vertical") == 0){
           Player.animation.Play("idle");
        }
 
        if (Input.GetKey(KeyCode.R) && Input.GetAxis("Vertical") == 0){
           regen = true;
        }
 
        if(regen && !Player.animation.isPlaying("faint"))
        {
          Player.animation.Play("faint");
          regen = false;
        }
 
}

Also take a look at : Unity - Scripting API: Animation.IsPlaying

Edited the solution check back ;)

No, the animation is still frozen, and I edit your code in exactly this way and it does not work...

Well can you the animation playing when u try in editor ? Did you tested that if the animation works correcctly without code ?

Yeah I already replace idle by faint to test it! Its work but when i dont touch keys of vertical axis.. it's wierd..

Try replacing Player.animation.Play with Player.animation.PlayQueued see if it helps http://docs.unity3d.com/Documentation/ScriptReference/Animation.PlayQueued.html

That’s not working… the animation don’t start, but “regen” is true.

You need to set regen back to false right after the .Play command.