Using Animator.SetTrigger(string)
Last updated
Last updated
You can use the Animator.SetTrigger
method to activate a trigger, which can then cause a transition to occur. The transition will take place as you have defined it and may not be instantaneous. However, this enables you to create more realistic transitions between animations. For more information, see Defining Animator transitions.
This example is like the Network state animation start/stopexample, in that is uses a combination of a NetworkStateTrigger_ToggleObjects
script to coordinate the network state, and an OnEnableDoEvent
script to call the desired methods.
Because triggers are set by an OnEnableDoEvent
script, one or both may be set when the scene loads. For example, if the game object is active when the scene loads, the trigger associated with the OnEnable
event will be set. If the default state for the NetworkState_ToggleObjects
script is 0, the game object will then be disabled, and the trigger associated with the OnDisable
event will be set. This can cause an animation to make multiple transitions between states when it first loads.
If you want the initial state for the NetworkState_ToggleObjects
script to be 0, we recommend that you set the object that has the OnEnableDoEvent
script to be inactive in Unity. This will prevent triggers from being set unnecessarily when the scene loads.
If you want the initial state for the NetworkState_ToggleObjects
script to be 1, set the default animation in the Animator to be the one associated with state 0 (AnimOne in the following diagram). This ensures that the trigger associated with the OnEnable
event is cleared correctly.
This example uses two buttons, which specifically set the state to 1 or 0, instead of a single button that toggles between the two states. Both methods are interchangeable and you can pick whichever matches your needs.
The following diagram shows an example of how to arrange the components in Unity, and the required references.