How to wait until animation is finished when using Animator? - unity3d

This is a beginner question that should be available from the first google result but I can't find it.
I have this method that plays an animation using an Animator:
IEnumerator popDownAnimation(string c)
{
animator = GetComponent<Animator>();
animator.Play("Pop Down Animation");
yield return new WaitUntil(() => animator.GetCurrentAnimatorStateInfo(0).normalizedTime > 1 && !animator.IsInTransition(0));
animator.Play("New State");
}
Can't remember where I got it from, but yield return new WaitUntil(() => animator.GetCurrentAnimatorStateInfo(0).normalizedTime > 1 && !animator.IsInTransition(0)); isn't working. It's instantly jumping from "Pop Down Animation" to "New State", so the "Pop Down Animation" doesn't have a chance to play.

Try this
IEnumerator popDownAnimation(string c)
{
animator = GetComponent<Animator>();
animator.Play("Pop Down Animation");
float animationLength = animator.GetCurrentAnimatorStateInfo(0).length;
yield return new WaitForSecondsRealtime(animationLength);
animator.Play("New State");
}
However, like #NotVeryGoodAtThis mentioned, I wouldn't do this in code unless you have a specific reason why you can't make it work using animation events or using parameters within the animator to transition between animation states. Designing your animation using Unity's Animator window and using states, parameters, and transitions will be easier to manage than doing it through code, especially as your animators become more complicated.

I would suggest using Animation events to do whatever you need. Just remember to make a public method and add the animation event at the end of your animation.

Related

Animator not animating a runtime instantiated child (UNITY)

I have a GameObject representing a room. As childs of this room I have 3 characters. Room has an animator component that control the synchronized animation of all characters.
The problem is I have another character that is instantiate from a prefab at runtime and this doesn't animate.
I tried several things:
//NOT WORKING
IEnumerator Start()
{
room.SetBool("e8", true);
yield return new WaitForSeconds(6);
...
}
//NOT WORKING
IEnumerator Start()
{
room.Rebind();
room.SetBool("e8", true);
yield return new WaitForSeconds(6);
...
}
//WORKING
IEnumerator Start()
{
yield return new WaitForEndOfFrame();
room.Rebind();
room.SetBool("e8", true);
yield return new WaitForSeconds(6);
...
}
The last try is working but the character looks stopped for an instant and suddenly jumps to the animation. I want the character animating from the beginning like the other characters.
My animator:
Simple solving
With current animator settings, this behavior is normal. You need to change your current animator using Any State section because when you use changing state from other states, Animation needs time to change your states. And for start Animator needs time for initializing, but if you will use Any State this will work.
Try doing something like this:
Entry different states
Either you can use what official documentation offers to you:
You can then add additional transitions from the Entry node to other states, to control whether the state machine should begin in a different state.
https://docs.unity3d.com/2019.4/Documentation/Manual/StateMachineTransitions.html
For example:

Unity Mecanim. How to reset animation before disabling a gameobject

Unity 2019.3.7f1
..
The artist I'm working with has made some animations for some UI stuff using the mecanim system Animator component.
I fire the animation with
Animator.SetTrigger("ParamaterName")
The gameobjects with the animator components, which are being animated, can get disabled by some of my scripts.
This can happen while the animation is playing..
So if the animation starts playing, and lets say the animation has made a button get bigger, then the gameobject gets disabled. When the gameobject is re-enabled (the animation is no longer playing) it is still big..
Is there a way to tell the Animator to go back to normal?
I have tried stuff like this in onEnable and OnDisable in a script on the GameObject
Animator.keepAnimatorControllerStateOnDisable = false
Animator.Play("normalState",0,0f);
Animator.playbackTime = 0f;
Animator.Update(0f);
This mecannim thing just seems like a black box as to how it works. I'm not familiar with it as I've always just used my own library to animate stuff that I've been using for donkeys years.
EDIT:
This was the solution...
private void Start()
{
Animator.keepAnimatorControllerStateOnDisable = true;
}
private void OnDisable()
{
Animator.Play("normalState",0,0f);
}
Make sure your keepAnimatorControllerStateOnDisable isn't set to true. Instead, you should set to false to clear the current state of the Animator controller
Animator.keepAnimatorControllerStateOnDisable = false
This way whenever you disable an object with an Animator, the Animator states and all its parameters go back to default.
Update
From your comments was able to understand the default is to have the button bigger. So, it's actually the other way around (set it to true, instead of false).
As you mention, write the following code
private void Start()
{
Animator.keepAnimatorControllerStateOnDisable = true;
}
private void OnDisable()
{
Animator.Play("normalState",0,0f);
}

Active a Unity animation if certain conditions are met?

I'm developing a 2d game in Unity and I ran into a problem. When trying to create animation transitions for one of my animations for some reason Unity instantly or very quickly deactivates my animation(like less then a second after I activated it). However when I don't have a transition conected to the animation the animation works fine. However I need to be able to transition the gameobject back to the state it was in before the animation after a certain condtion is met and so I cant leave the animation running. Does anyone know how I can solve this problem?
Ive tried switching the way I activate the animations to see if it might be related to this by trying both a bool and trigger as the condition that determines when a transition should happen but the same problem arrises
THis is a rough outline of how I activate the animation
public class InteractControl : MonoBehaviour, IPooledObject
{
public static float timeLeft = 10f;
public void OnObjectSpawn()
{
anim = GetComponent<Animator>();
}
// Change this method to just be a temporary obstacle
void Update()
{
timeLeft -= Time.deltaTime;
if (timeLeft > 0)
{
anim.enabled = true;
}
if (timeLeft < 0)
{
anim.SetTrigger("FollowAd");
}
}
}
Ad Follow with transition:
Ad Follow without transition:
Transition Settings:
The animation should activate if timeLeft is bigger than 0 and deactivate as soon as it is smaller then 0 and return the the gameobject to the state it was in before the animation started. Right now if Ad Follow_ has no transition the animation works when called upon but doesn't deactivate. if Ad Follow_ has an empty state connected to it to which it should transition should
anim.SetTrigger("FollowAd");
be called like shown above it works for less then a second or not at all and then switches straight back to the default state. It should only switch back when timeLeft < 0.
You can create a public RuntimeAnimatorController animCon for your required animation. When your conditions are met. You can do anim.runtimeanimatorcontroller = animCon;.
And When the condition is false do this anim.runtimeanimatorcontroller = null;. Its not the best way but its quick and better then most.

Randomized Attack Animation RPG

First of all, I'm quite noob with animator and animation systems in unity.
What I'm trying to achieve (and I was trying with Animator component) is a randomized attack only while I keep my mouse button pressed on the enemy and which completes the execution of the attack clip that is playing even if i release the button meanwhile.
I tried adding my 2 attack animations to a list and play it, with something like
anim.Play(Random.Range(0, list.Count))
...but I don'tknow if the problem is that while I keep pressed one animation cancels the other or what.
Therefore I prefer to ask, because I'm probably doing things in the wrong way.
Thank you.
Yes the issue is probably what you said: You have to wait until one Animation finished before starting a new one otherwise you would start a new animation every frame.
You could use a Coroutine (also check the API) to do that.
Ofcourse the same thing could be implemented also only in Update without using a Coroutine but most of the times that becomes really cluttered and sometimes even more complicated to handle. And there is not really any loss or gain (regarding performance) in simply "exporting" it to a Coroutine.
// Reference those in the Inspector or get them elsewhere
public List<AnimationClip> Clips;
public AnimationClip Idle;
private Animator _anim;
// A flag to make sure you can never start the Coroutine multiple times
private bool _isAnimating;
private void Awake()
{
_anim = GetComponent<Animator>();
}
private void Update()
{
if(Input.GetMouseButtonDown(0)
{
// To make sure there is only one routine running
if(!_isAnimating)
{
StartCoroutine(RandomAnimations());
}
}
// This would immediately interrupt the animations when mouse is not pressed anymore
// uncomment if you prefer this otherwise the Coroutine waits for the last animation to finish
// and returns to Idle state afterwards
//else if(Input.GetMouseButtonUp(0))
//{
// // Interrupts the coroutine
// StopCoroutine (RandomAnimations());
//
// // and returns to Idle state
// _anim.Play(Idle.name);
//
// // Reset flag
// _isAnimating = false;
//}
}
private IEnumerator RandomAnimations()
{
// Set flag to prevent another start of this routine
_isAnimating = true;
// Go on picking clips while mouse stays pressed
while(Input.GetMouseButton(0))
{
// Pick random clip from list
var randClip = Clips[Random.Range(0, Clips.Count)];
// Switch to the random clip
_anim.Play(randClip.name);
// Wait until clip finished before picking next one
yield return new WaitForSeconds(randClip.length);
}
// Even if MouseButton not pressed anymore waits until the last animation finished
// then returns to the Idle state
// If you rather want to interrupt immediately if the button is released
// skip this and uncomment the else part in Update
_anim.Play(Idle.name);
// Reset flag
_isAnimating = false;
}
Note that this way of randomizing does not provide things like "Don't play the same animation twice in a row" or "Play all animations before repeating one".
If you want this checkout this answer to a very similar question. There I used a randomized list to run through so there are no doubles

Horrors of OnPointerDown versus OnBeginDrag in Unity3D

I'm concerned over the difference between OnPointerDown versus OnBeginDrag in single-finger movement code.
(In the latest Unity paradigm of using a physics raycaster: so, finally, Unity will properly ignore touch on the UI layer.
So from 2015 onwards what you must do is this:
Forget about the crap traditional Input or Touches system which are pointless crap and don't work
Add an empty game object with a usually BoxCollider2D, likely bigger than the screen. Make the layer called say "Draw". Physics settings, "Draw" interacts with nothing
Simply add to the camera, a 2D or 3D physics raycaster. Event mask the "Draw" layer.
Do a script like below and put it on.
(Tip - don't forget to simply add an EventSystem to the scene. Bizarrely, Unity does not do this automatically for you in some situations but Unity does do it automatically for you in other situations, so it's annoying if you forget!)
But here's the problem.
There has got to be some subtle difference between using OnPointerDown versus OnBeginDrag (and the matching end calls). (You can just swap the action in the following code sample.)
Naturally Unity offers no guidance on this; the following code beautifully rejects stray grabs and also flawlessly ignores your UI layer (thanks Unity! at last!) but I am mystified about the difference between the two approaches (begin drag V. begin touch) and I cannot in anyway find the logical difference between the two in unit testing.
What's the answer?
/*
general movement of something by a finger.
*/
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class FingerMove:MonoBehaviour,
IPointerDownHandler,
IBeginDragHandler,
IDragHandler,
IPointerUpHandler,
IEndDragHandler
{
public Transform moveThis;
private Camera theCam;
private FourLimits thingLimits;
private Vector3 prevPointWorldSpace;
private Vector3 thisPointWorldSpace;
private Vector3 realWorldTravel;
public void Awake()
{
theCam = Camera.main or whatever;
}
public void OnMarkersReady() // (would be EVENT DRIVEN for liveness)
{
thingLimits = Grid.liveMarkers. your motion limits
}
private int drawFinger;
private bool drawFingerAlreadyDown;
public void OnPointerDown (PointerEventData data)
{
Debug.Log(" P DOWN " +data.pointerId.ToString() );
}
public void OnBeginDrag (PointerEventData data)
{
Debug.Log(" BEGIN DRAG " +data.pointerId.ToString() );
if (drawFingerAlreadyDown == true)
{
Debug.Log(" IGNORE THAT DOWN! " +data.pointerId.ToString() );
return;
}
drawFinger = data.pointerId;
drawFingerAlreadyDown=true;
prevPointWorldSpace = theCam.ScreenToWorldPoint( data.position );
}
public void OnDrag (PointerEventData data)
{
Debug.Log(" ON DRAG " +data.pointerId.ToString() );
if (drawFingerAlreadyDown == false)
{
Debug.Log(" IGNORE THAT PHANTOM! " +data.pointerId.ToString() );
}
if ( drawFinger != data.pointerId )
{
Debug.Log(" IGNORE THAT DRAG! " +data.pointerId.ToString() );
return;
}
thisPointWorldSpace = theCam.ScreenToWorldPoint( data.position );
realWorldTravel = thisPointWorldSpace - prevPointWorldSpace;
_processRealWorldtravel();
prevPointWorldSpace = thisPointWorldSpace;
}
public void OnEndDrag (PointerEventData data)
{
Debug.Log(" END DRAG " +data.pointerId.ToString() );
if ( drawFinger != data.pointerId )
{
Debug.Log(" IGNORE THAT UP! " +data.pointerId.ToString() );
return;
}
drawFingerAlreadyDown = false;
}
public void OnPointerUp (PointerEventData data)
{
Debug.Log(" P UP " +data.pointerId.ToString() );
}
private void _processRealWorldtravel()
{
if ( Grid. your pause concept .Paused ) return;
// potential new position...
Vector3 pot = moveThis.position + realWorldTravel;
// almost always, squeeze to a limits box...
// (whether the live screen size, or some other box)
if (pot.x < thingLimits.left) pot.x = thingLimits.left;
if (pot.y > thingLimits.top) pot.y = thingLimits.top;
if (pot.x > thingLimits.right) pot.x = thingLimits.right;
if (pot.y < thingLimits.bottom) pot.y = thingLimits.bottom;
// kinematic ... moveThis.position = pot;
// or
// if pushing around physics bodies ... rigidbody.MovePosition(pot);
}
}
And here's a handy thing. Save typing with the same thing for 3D scenes, using the little-known but exquisite
pointerCurrentRaycast
here's how... notice the excellent
data.pointerCurrentRaycast.worldPosition
call courtesy Unity.
public class FingerDrag .. for 3D scenes:MonoBehaviour,
IPointerDownHandler,
IDragHandler,
IPointerUpHandler
{
public Transform moveMe;
private Vector3 prevPointWorldSpace;
private Vector3 thisPointWorldSpace;
private Vector3 realWorldTravel;
private int drawFinger;
private bool drawFingerAlreadyDown;
public void OnPointerDown (PointerEventData data)
{
if (drawFingerAlreadyDown == true)
return;
drawFinger = data.pointerId;
drawFingerAlreadyDown=true;
prevPointWorldSpace = data.pointerCurrentRaycast.worldPosition;
// in this example we'll put it under finger control...
moveMe.GetComponent<Rigidbody>().isKinematic = false;
}
public void OnDrag (PointerEventData data)
{
if (drawFingerAlreadyDown == false)
return;
if ( drawFinger != data.pointerId )
return;
thisPointWorldSpace = data.pointerCurrentRaycast.worldPosition;
realWorldTravel = thisPointWorldSpace - prevPointWorldSpace;
_processRealWorldtravel();
prevPointWorldSpace = thisPointWorldSpace;
}
public void OnPointerUp (PointerEventData data)
{
if ( drawFinger != data.pointerId )
return;
drawFingerAlreadyDown = false;
moveMe.GetComponent<Rigidbody>().isKinematic = false;
moveMe = null;
}
private void _processRealWorldtravel()
{
Vector3 pot = moveMe.position;
pot.x += realWorldTravel.x;
pot.y += realWorldTravel.y;
moveMe.position = pot;
}
}
I want to start by saying that Input and Touches are not crappy.They are still usefull and were the best way to check for touch on mobile devices before OnPointerDown and OnBeginDrag came along. OnMouseDown() you can call crappy because it was not optimized for mobile. For a beginner who just started to learn Unity, Input and Touches are their options.
As for your question, OnPointerDown and OnBeginDrag are NOT the-same. Although they almost do the-same thing but they were implemented to perform in different ways. Below I will describe most of these:
OnPointerDown:
Called when there is press/touch on the screen (when there is a click or finger is pressed down on touch screen)
OnPointerUp:
Called when press/touch is released (when click is released or finger is removed from the touch screen)
OnBeginDrag:
Called once before a drag is started(when the finger/mouse is moved for the first time while down)
OnDrag :
Repeatedly called when user is dragging on the screen (when the finger/mouse is moving on the touch screen)
OnEndDrag:
Called when drag stops (when the finger/mouse is no longer moving on the touch screen).
OnPointerDown versus OnBeginDrag and OnEndDrag
OnPointerUp will NOT be called if OnPointerDown has not been called. OnEndDrag will NOT be called if OnBeginDrag has not been called. Its like the curly braces in C++,C#, you open it '{' and you close it '}'.
THE DIFFERENCE:
OnPointerDown will be called once and immediately when finger/mouse is on the touch screen. Nothing else will happen until there is a mouse movement or the finger moves on the screen then OnBeginDrag will be called once followed by OnDrag.
These are made for doing advanced usage such such as custom UI with controls that is not included in Unity.
WHEN TO USE EACH ONE:
1. When you have to implement a simple click button, for example, Up,Down, Shoot Button on the screen, you only need OnPointerDown to detect the touch. This should work for Sprite Images.
2. When you have to implement a custom toggle switch and you want it to be realistic so that the player can drag to left/right or up/down to toggle it then you need OnPointerDown , OnBeginDrag , OnDrag , OnEndDrag , OnPointerUp. You need to write your code in this order to have a smooth Sprite/Texture transition on the screen. Some toggle switches are made to be to clicked and it will toggle. Some people prefer to make it look realistic by making it so that you have to drag it in order to toggle it.
3. Also when you want to implement a Generic re-usable pop-up window that is draggable, you also need to use those 5 functions (OnPointerDown , OnBeginDrag , OnDrag , OnEndDrag , OnPointerUp).
First detect when there is a click(OnPointerDown), check to make sure that the Sprite clicked is the right one you want to move. Wait for player to move(OnBeginDrag) their finger/mouse. Once they start dragging, maybe you can call a coroutine function with while loop that will start moving the Sprite and inside that coroutine, you can smooth the movement of the Sprite with Time.deltaTime or any other preferred method.
Since OnBeginDrag is called once, it is a good place to start the coroutine.
As the player continue to drag the Sprite, OnDrag will be called repeatedly. Use the OnDrag function to get the current location of the finder and update that to a Vector3 that the coroutine that is already running will use to update the position of the Sprite. When the player stops moving their finger/mouse on the screen, OnEndDrag is called and you can boolean variable and tell the coroutine to stop updating the position of the Sprite. Then, when the player releases their finger(OnPointerUp) you can then stop the coroutine with the StopCoroutine function.
Because of OnBeginDrag we we are able to start coroutine once drag started while waiting for drag to end. It wouldn't make sense to start that coroutine in OnPointerDown because that means that each time player touches the screen, a coroutine would be started.
Without OnBeginDrag, we have to use boolean variable to make the coroutine start only once in the OnDrag function which is called every time or else there would be coroutine running everywhere and unexpected movement of the Sprite will occur.
4. When you want to determine how long player moved their finger. Example of this is that famous game called Fruit Ninja. Lets just say you want to determine far the player swiped on the screen.
First, wait until OnPointerDown is called, wait again until OnBeginDrag is called, then you can get the current position of the finger inside OnBeginDrag function because OnBeginDrag is called before the finger starts moving. After the finger is released, OnEndDrag is called. Then you can get the current position of finger again. You can use these two positions to check how far the finger moved by subtracting them.
If you instead decide to use OnPointerDown as the place to get the first position of the finger, you will get a wrong result because if the player swipes right, then waits and swipes left then waits again and swipe up without releasing their finger after each swipe, the only good result you have is the first swipe(right swipe). The left and the up swipe will have invalid values because that first value you got when OnPointerDown was called is the value you are still using. This is because the player never removed their finger from the screen so therefore, OnPointerDown is never called again and the first old old value is still there.
But when you use OnBeginDrag instead of OnPointerDown, this problem will be gone because when the finger stops moving, OnEndDrag is called and when it starts moving again OnBeginDrag is called once again causing the first position to be overwritten with the new one.
The difference is that OnBeginDrag doesn't get called until the touch/mouse has moved a certain minimum distance, the drag threshold. You can set the drag threshold on the Event System component.
This is necessary for when you have a hierarchy of objects with different ways of handling input, especially scrollviews. Imagine you have a scrollview with a vertical stack of cells, each with a button in it. When the touch first starts on one of the buttons, we don't know whether the user is tapping a button or dragging the scrollview. It isn't until the touch gets dragged for the drag threshold that we know it is a drag and not a tap.