Search code examples
unreal-blueprintunreal-engine5

How to control NPC animation from GUI button click (Unreal)


I have a number of animation sequences connected to an ENUM Blend Pose node. I can manually switch this enum value in the Anim Preview panel.

Now I wish to control this enum value from a bunch of buttons added to a User Widget. The widget is instantiated within the Level BP.

When I edit the onClick events on the buttons, I do not know how to get a reference to my enum variable (which I have exposed as Public in the Anim Blueprint's settings).

Essentially, each button is designed to change this variable to a unique value, which then should cause the appropriate animation to play within the Blend Pose.

How do I let the Widget have access to that variable? Or vice versa, how could I create a variable on the blueprint that can be used to set the Enum value on the Blend Pose?

Please note that I am using the visual blueprint editor, not C++ at this time.


Solution

  • I am coming from a 100% C++ background, so I may have some options on my mind that are not entirely working in BP, but we'll get to that.

    1. I would not use the level blueprint at all for anything. Instead use your GameMode or GameState for spawning the UserWiget. The GameMode and GameState are accessible via the GetGameMode node. Keep in mind that in multiplayer scenarios, only the GameState is available to all while the GameMode can only be accessed by the host or dedicated server, but that is probably irrelevant for you.
    2. After spawning the widget assign it to a public variable of its type, so you can get it from the outside.
    3. In your actor (not animation blueprint) you can access the GameMode easily using the GetGameMode node. You have to cast it to your specific GameMode to get to the variable of the widget. For the GameState use GetGameState.
    4. Now you have multiple options to connect everything together. You could for example pass your actor to the UI and store it as a variable there. The UI can then simply call a custom function like "SetAnimationState" that you create on the actor for each button. Your actor can pass the enum value down to the animation blueprint. Using your skeletal meshes GetAnimInstance node.

    This is one simple way I can think of. You could also work with an event dispatcher that broadcasts whenever a button is pressed and your actor is subscribed to it to get notified.

    I hope any of this helps.