Search Unity

Question Animator Play at a specific time does not work combined with SetTrigger

Discussion in 'Animation' started by ClaudiaTheDev, Jun 25, 2021.

  1. ClaudiaTheDev

    ClaudiaTheDev

    Joined:
    Jan 28, 2018
    Posts:
    331
    I have several NPCs using the same animator with an idle animation. To avoid that all NPCs move the exact same way (being sync) i play the animator with a random value in Start() so it looks more natural:

    Code (CSharp):
    1. animator.Play(0, -1, Random.value);
    This works like intended (first paramater 0 is for current state which is the default state).

    But here is now my big issue and problem (maybe bug?):

    Some Npcs do different things, like sitting, or standing. So i control also in Start() the animation which should be played by setting a trigger. When i set the trigger playing at a random value does not work, anymore and all NPCs are sync again.

    Code (CSharp):
    1.  private void Start()
    2.         {
    3.             if (!string.IsNullOrEmpty(animationTrigger))
    4.             {
    5.                 animator.SetTrigger(animationTrigger);
    6.                
    7.                 if (randomStartTime)
    8.                 {
    9.                     animator.Play(0, -1, Random.value);
    10.                 }
    11.             }  
    12.         }
    Maybe the state is not updated immediate after i call SetTrigger? I can only think of making like a workaround and call animator.Play in the next frame but maybe there is an easier solution?

    Please help me♥!
     
  2. Kybernetik

    Kybernetik

    Joined:
    Jan 3, 2013
    Posts:
    2,570
    Calling SetTrigger won't actually have any effect until the next animation update, so calling Play with -1 as the state will indicate the previous state before the trigger's transition occurs, which then gets replaced by the transition. So you'd need to wait a frame or just use Play/CrossFade instead of the trigger so you can pass the random time there.

    You might also be interested in Animancer (link in my signature) which lets you control everything directly in code instead of using Animator Controllers. It lets you directly set the time of any state whenever you want and doesn't force you to wait a frame between commands.
     
  3. ClaudiaTheDev

    ClaudiaTheDev

    Joined:
    Jan 28, 2018
    Posts:
    331
    Thank you for your explanation! I called it in the first LateUpdate (Update was too early) and it works♥!

    Animancer looks interesting! Not for this project cause i already use a lot of my own custom code controlling animations but for my future projects it's something i keep in mind!