Handling instancing/transitions of prefab at runtime, using StateMachineBehaviour

Hi,

I’have a menu that is being filled at runtime, based on a previous selection.
So I’ve a prefab that I instantiate as usual in a loop.

Every prefab comes with an Animator that handles enter and exit transitions.

What I’d like to achieve is the following, using StateMachineBehavior (almost c# pseudocode):

// ENTER Animation
onStateEnter() {
    menuHandler.drawItems()
}

// EXIT Animation
onStateEnter() {
    menuHandler.destroyItems()
}

// menuHandler drawItems
foreach(item in items) {
    go = Instantiate(itemPrefab, position, rotation);
    go.animator.trigger("Entering")
}

// menuHandler destroyItems
foreach(go in items) {
    Destroy(go)

}

And then have this MACHINE STATES:

  • ENTER
  • ENTERING
  • EXITING
  • EXIT

The -ing states are where the animation occurs.

Is this the right approach to handle runtime children animations in a sensible way?
Am I missing something else?

StateMachineBehaviour reference: Unity - Scripting API: StateMachineBehaviour

I suggest you don’t rely your logic on state machine behaviours. While it’s okay for things like sfx/vfx, it will break your program because there are a lot of conditions for certain envents to be skipped. Also their order is messed. Next state enter may come out before current state exit, for instance.

1 Like

Thanks palex-nx.
I actually discarded the state machine behaviour idea.

I ended up with this solution (almost pseudocode)

transitionRunning = true
targetState = "Exited"
animatingCount = children.count

while(transitionRunning)
  
    foreach (child in children)

        if child.animator.GetCurrentAnimatorStateInfo(0).isName(targetState)
            animatingCount -= 1
 
     if (animatingCount <= 0)
        // dispatch the proper event
        OnExitTransitionEvent.Raise()
        transitionRunning = false
     else
        yield return WaitForEndOfFrame

Still wondering wether it is the correct approach (I’m new to Unity)

Still none. Everyone invents it’s own and noose succedeed to replace all of them. But there are three common approaches to animations serving different purposes. Those are Timeline, Animator and Playables.

So? Is there any example or reference you can point?

No, i cant point any decent example and say I suggest you do it this way. With multiple approaches you need to chose carefully what fits where in your game best.

So you’re telling me that my approach is not correct, and that there are three common approaches to do it.
But you can’t give me a reference to any of those?

No im not telling yours is not correct, its pretty okay to handle animator this way, im telling you also there are timeline and playables, check may be they fit better for your game or some aspects of it