Unity C# Animation is only playing the first frame - c#

I am trying to make a character play a specific animation when pressing the R button. I would like him to play the whole animation and then stop once it has run a cycle.
The issue now is that when I press "R" the animation only plays for a frame and no animation plays at all.
I started with this statement below.
void Update ()
{
if (Input.GetKeyDown(KeyCode.R))
{
anim.Play("Ready");
}
}
I then read that it might be better to create a bool instead, if the bool is true -> play Animation.
public bool ready;
void Update ()
{
if (Input.GetKeyDown(KeyCode.R))
{
ready = !ready;
}
if (ready == true)
{
anim.Play("Ready");
}
}
When bool ready is true, the animation plays one frame and then the character becomes static. If the bool the gets false again, the character returns to his idle animation.
My latest attempt to making this work is by structuring the code like this:
if (Input.GetKeyDown(KeyCode.R))
{
ready = !ready;
if(ready == true)
{
anim.Play("Ready");
}
}
However this only causes the animation to play a very small amount of frames until going back to the idle animation. Even though ready stays true.
I am not using the "Animator component" but rather the "Animation component" instead. This are the settings of it: Animation Component
Could it be the void Update() causing the issue?
Also, is there a way to make sure the animation only plays for one cycle and then stops?

Your method looks valid. Are there chances that your imported animation isn't?
You should use the Animator as suggested:
drop your clips in the Animator window,
right click on the default state > "make transition", release on the next clip,
create a parameter of type bool named "ready",
assign this parameter in the transition from idle to the next state (select the arrow and click the "+" button at the bottom of the component in the Inspector window, select your parameter),
in your script, you just have to call:
myAnimator.SetBool("ready", true);
There are a lot of benefits of using the Animator :
handle many animation clips, automatic transitions, preview, and more features with "humanoid" rigs (in the model import settings)...

Related

The animation state .. could not be played because it couldn't be found?

I am trying to start an animation by pressing a key on my keyboard.
For this I am using the following code:
[HideInInspector] public Animation animation;
private void Start()
{
animation = GetComponent<Animation>();
}
private void Update()
{
if (Input.GetKeyDown("1"))
{
animation.Play("AnimationName");
}
}
This gives me the following error:
The animation state AnimationName could not be played because it
couldn't be found!
Although, the animation DOES start, but how can I clear this error?
I think the only possible explaination is that your animation clip is not marked as Legacy.
https://www.unity3dtips.com/zh/the-animation-state-could-not-be-played-because-it-couldnt-be-found/
EDIT with step by step here:
Animations must be marked as legacy to be used with the animation component.
In the project window select the animation clips you’re trying to play.
Set the inspector to debug mode which exposes hidden variables, in this case it’ll make the “Legacy” checkbox appear.Unity Inspector Debug Mode
Tick the “Legacy” checkbox and change the inspector back to normal mode.
Unity Inspector Animation Clip Legacy Checkbox
But there is one thing you should know: you should avoid, if possible, the old legacy way to play animation.
Learn how to use an Animator component. Just create an animator, assign your animation clip, decide a boolean for start the animation in the animator component and set it to true in your code (for basic use).
Sure there is some things to do beside code but it will be easier to control your animation, bleand different animations and change them to your needs (it's for example much easier to loop or stop the animation at some point).
It would be also easier to understand when it start and when is playing.
Another thing to check is the legacy 'Animation' component on your gameObject that is supposed to perform the animation. In my case things were marked as legacy for the animation on the imported animation but somehow when adjusting settings on my import it dropped the animation it was complaining about from the actual 'Animation' component so once I added it things worked as expected
Inspector in Debug mode showed my animation marked as 'Legacy' true
My Animation component showed the missing animation

How to make model jump to the first animation frame after enable it?

Unity C# question.
I have a model with animator controller. I need to make it "jump" to the first frame of its animation right before I disable the model via SetActive(false). So if I disable the model during its animation, and then enable it again, the model should reset its animation and appear in "default" state, so I could start animation from the beginning.
The problem is that if I disable and enable the model during the animation, it appears frozen in the same frame which it has when I disabled it.
I tried add a transition from "any state" to the default state, set transition duration to 0, and add "reatart" bool parametr to trigger the transition. And then:
myObject.SetBool("restart", true);
myObject.SetActive(false);
But it doesn't work, the object appears frozen in the middle of animation again.
I thought maybe it still needs some time for transition, so I tried as a workaround to use coroutine:
- disable only mesh renderer
- In Animator start transition to the first frame of animation
(transition duration is 0)
- Wait a bit
- SetActive(false)
But when I enable it again it is still frozen in the middle of the animation.
Why is it happening? And how can it be fixed?
Thank you very much in advance!
Hereis the code example:
public void disableObject(){
StartCoroutine(disableObjectCoroutine());
}
public void enableObject(){
myObject.GetComponent<Renderer>().enabled = true;
myObject.SetActive(true);
}
IEnumerator disableObjectCoroutine(){
myObject.GetComponent<Renderer>().enabled = false;
myObject.GetComponent<Animator> ().SetBool ("restart", true);
yield return new WaitForSeconds(.1f);
myObject.GetComponent<Animator> ().SetBool ("mainAnimation", false);
myObject.SetActive(false);
}
You can try somethink like that:
int layer = 0;
int hashName = myAnimator.GetCurrentAnimatorStateInfo(0).shortNameHash; //get current animation name
myAnimator.Play(hashName, layer, 0); // 0 means first frame
myObject.SetActive(false);

Run new animation only when previous one is finished

I'm new to Unity and I'm struggling with configuring my animations properly. I have attack animation which must be played if you press the spacebar once and if you hold it it should play until you release. My problem is that once you release the spacebar the animator instantly returns to the previous state. I've read some answer on the Unity Q&A site but they are all concerning a script that runs the animations, I don't use any script to run mine I'm simply setting them up in the animator. How can I fix this ? The way I change the animation is by switching the value of a boolean variable like this :
if(Input.GetKeyDown(KeyCode.Space))
{
IsAttacking = true;
}
if(Input.GetKeyUp(KeyCode.Space))
{
IsAttacking = false;
}
playerAnimator.SetBool("IsAttacking", IsAttacking);
My project is in 2D if it matters.
Click this ->
Exit Time
Inside of the animator you have your clips. Clicking on a clip with bring up this inspector view. You'll want to check Has Exit Time'.
Then you'll want to set your exit time to 1 and your transition duration to 0.
By setting those values, you're telling the animator that this animation MUST finish before moving on to the next one.

How to play animations while the game is paused (timescale = 0)

I am trying to pause a game in Unity using by setting timeScale to 0 when the pause panel comes up, and setting it back to 1 when the panel is disabled. The problem I am having is that when I Pause, the buttons on the panel are not showing their animation as the time scale is 0. Is there anyway around this? Or should I find another way to do the pause without using the timescale?
In your Animator component look for Update Mode option and select Unscaled Time. Like this :
A possibility is to maintain state of your game using Enum. e.g., define an enum as:
enum GameState
{
Started,
Loading,
Playing,
Paused,
Completed
}
Declare a variable of type GameState in your session or any place where access is easy to you, then compare:
if(currentGameState == GameState.Playing)
{
// Play logic here
}
To fix your animations issue . Simply make the animation to play in unscaled time. That way the animation plays even if Time.timeScale is 0. You can do this by setting the update mode of the animator to Unscaled time.

Enabling Animator causes flicker?

In Unity 3D (2D mode), I have a few Game Objects linked with Animator, and animation made with Animation Timeline. The animation is initially disabled:
public GameObject car;
Animator carAnim;
void Start() {
carAnim = car.GetComponent<Animator>();
carAnim.enabled = false;
}
Then, with an input event, the animation is set to enable:
void Update() {
if(Input.GetKeyDown(0)) {
carAnim.enabled = true;
}
}
However, when the animation starts to play, the whole screen flickers once. How to remove the flicker?
I think the problem is that you're trying to enable and disable Animator component at runtime. Animator was not designed to be used like this. If you want to play animation in certain point of time, just keep Animator enabled, create 2 states - "Idle" and "YourAnimation", create transition between them and control it with some bool parameter.
Much simple way is to use Animation component (if you don't need Mecanim and transitions between states), where you can play animation with just one line of code:
gameObject.GetComponent<Animation>().Play("MyAnimation");

Categories

Resources