Skip to content

Commit 2d9f786

Browse files
fix: NetworkAnimator Synchronizing transition twice [MTT-3564] (#2084)
* fix This fixes the issue where transitions were being both triggered and the change in animation state (i.e. transition state) was being synchronized and applied to clients already transitioning which would cause any StateMachineBehaviours to have their OnStateEnter method invoked twice. * fix Making adjustments to account for changes to the Transition state update vs trigger update fix. * test Adding the additional StateMachineBehaviour (CheckStateEnter) to validate this fix. Adjusting two tests for this fix. Includes the animation related assets needed for the test. * style adding additional comments for some changes that were not obvious to the fix. * update removing code used to debug * style MTT-3564 updating changelog. * style correcting grammar in comment * style slight adjustment to the comment * style * update removing more debug related code. * style minor integration test variable rename.
1 parent 045cac3 commit 2d9f786

File tree

7 files changed

+210
-32
lines changed

7 files changed

+210
-32
lines changed

com.unity.netcode.gameobjects/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ Additional documentation and release notes are available at [Multiplayer Documen
2020
- Fixed issue when attempting to spawn a parent `GameObject`, with `NetworkObject` component attached, that has one or more child `GameObject`s, that are inactive in the hierarchy, with `NetworkBehaviour` components it will no longer attempt to spawn the associated `NetworkBehaviour`(s) or invoke ownership changed notifications but will log a warning message. (#2096)
2121
- Fixed an issue where destroying a NetworkBehaviour would not deregister it from the parent NetworkObject, leading to exceptions when the parent was later destroyed. (#2091)
2222
- Fixed issue where `NetworkObject.NetworkHide` was despawning and destroying, as opposed to only despawning, in-scene placed `NetworkObject`s. (#2086)
23+
- Fixed `NetworkAnimator` synchronizing transitions twice due to it detecting the change in animation state once a transition is started by a trigger. (#2084)
2324
- Fixed issue where `NetworkAnimator` would not synchronize a looping animation for late joining clients if it was at the very end of its loop. (#2076)
2425
- Fixed issue where `NetworkAnimator` was not removing its subscription from `OnClientConnectedCallback` when despawned during the shutdown sequence. (#2074)
2526
- Fixed IsServer and IsClient being set to false before object despawn during the shutdown sequence. (#2074)

com.unity.netcode.gameobjects/Components/NetworkAnimator.cs

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@ public class NetworkAnimator : NetworkBehaviour
163163
internal struct AnimationMessage : INetworkSerializable
164164
{
165165
// state hash per layer. if non-zero, then Play() this animation, skipping transitions
166+
internal bool Transition;
166167
internal int StateHash;
167168
internal float NormalizedTime;
168169
internal int Layer;
@@ -427,6 +428,7 @@ internal void ServerSynchronizeNewPlayer(ulong playerId)
427428

428429
var animMsg = new AnimationMessage
429430
{
431+
Transition = m_Animator.IsInTransition(layer),
430432
StateHash = stateHash,
431433
NormalizedTime = normalizedTime,
432434
Layer = layer,
@@ -442,6 +444,9 @@ private void OnClientConnectedCallback(ulong playerId)
442444
m_NetworkAnimatorStateChangeHandler.SynchronizeClient(playerId);
443445
}
444446

447+
/// <summary>
448+
/// Checks for changes in both Animator parameters and state.
449+
/// </summary>
445450
internal void CheckForAnimatorChanges()
446451
{
447452
if (!IsOwner && !IsServerAuthoritative() || IsServerAuthoritative() && !IsServer)
@@ -482,6 +487,7 @@ internal void CheckForAnimatorChanges()
482487

483488
var animMsg = new AnimationMessage
484489
{
490+
Transition = m_Animator.IsInTransition(layer),
485491
StateHash = stateHash,
486492
NormalizedTime = normalizedTime,
487493
Layer = layer,
@@ -744,7 +750,13 @@ internal unsafe void UpdateParameters(ParametersUpdateMessage parametersUpdate)
744750
/// </summary>
745751
private unsafe void UpdateAnimationState(AnimationMessage animationState)
746752
{
747-
if (animationState.StateHash != 0)
753+
if (animationState.StateHash == 0)
754+
{
755+
return;
756+
}
757+
758+
var currentState = m_Animator.GetCurrentAnimatorStateInfo(animationState.Layer);
759+
if (currentState.fullPathHash != animationState.StateHash || m_Animator.IsInTransition(animationState.Layer) != animationState.Transition)
748760
{
749761
m_Animator.Play(animationState.StateHash, animationState.Layer, animationState.NormalizedTime);
750762
}
@@ -830,6 +842,10 @@ private unsafe void SendAnimStateServerRpc(AnimationMessage animSnapshot, Server
830842
[ClientRpc]
831843
private unsafe void SendAnimStateClientRpc(AnimationMessage animSnapshot, ClientRpcParams clientRpcParams = default)
832844
{
845+
if (IsServer)
846+
{
847+
return;
848+
}
833849
var isServerAuthoritative = IsServerAuthoritative();
834850
if (!isServerAuthoritative && !IsOwner || isServerAuthoritative)
835851
{
@@ -879,11 +895,7 @@ private void SendAnimTriggerServerRpc(AnimationTriggerMessage animationTriggerMe
879895
[ClientRpc]
880896
internal void SendAnimTriggerClientRpc(AnimationTriggerMessage animationTriggerMessage, ClientRpcParams clientRpcParams = default)
881897
{
882-
var isServerAuthoritative = IsServerAuthoritative();
883-
if (!isServerAuthoritative && !IsOwner || isServerAuthoritative)
884-
{
885-
m_Animator.SetBool(animationTriggerMessage.Hash, animationTriggerMessage.IsTriggerSet);
886-
}
898+
m_Animator.SetBool(animationTriggerMessage.Hash, animationTriggerMessage.IsTriggerSet);
887899
}
888900

889901
/// <summary>
@@ -900,8 +912,13 @@ public void SetTrigger(string triggerName)
900912
/// <param name="setTrigger">sets (true) or resets (false) the trigger. The default is to set it (true).</param>
901913
public void SetTrigger(int hash, bool setTrigger = true)
902914
{
903-
var isServerAuthoritative = IsServerAuthoritative();
904-
if (IsOwner && !isServerAuthoritative || IsServer && isServerAuthoritative)
915+
// MTT-3564:
916+
// After fixing the issue with trigger controlled Transitions being synchronized twice,
917+
// it exposed additional issues with this logic. Now, either the owner or the server can
918+
// update triggers. Since server-side RPCs are immediately invoked, for a host a trigger
919+
// will happen when SendAnimTriggerClientRpc is called. For a client owner, we call the
920+
// SendAnimTriggerServerRpc and then trigger locally when running in owner authority mode.
921+
if (IsOwner || IsServer)
905922
{
906923
var animTriggerMessage = new AnimationTriggerMessage() { Hash = hash, IsTriggerSet = setTrigger };
907924
if (IsServer)
@@ -911,9 +928,11 @@ public void SetTrigger(int hash, bool setTrigger = true)
911928
else
912929
{
913930
SendAnimTriggerServerRpc(animTriggerMessage);
931+
if (!IsServerAuthoritative())
932+
{
933+
m_Animator.SetTrigger(hash);
934+
}
914935
}
915-
// trigger the animation locally on the server...
916-
m_Animator.SetBool(hash, setTrigger);
917936
}
918937
}
919938

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
using System.Collections.Generic;
2+
using UnityEngine;
3+
using Unity.Netcode;
4+
5+
namespace TestProject.RuntimeTests
6+
{
7+
public class CheckStateEnterCount : StateMachineBehaviour
8+
{
9+
public static Dictionary<ulong, Dictionary<int, List<AnimatorStateInfo>>> OnStateEnterCounter = new Dictionary<ulong, Dictionary<int, List<AnimatorStateInfo>>>();
10+
public static bool IsIntegrationTest;
11+
public static bool IsManualTestEnabled = true;
12+
13+
public static void ResetTest(bool isIntegrationTest = true)
14+
{
15+
IsIntegrationTest = isIntegrationTest;
16+
IsManualTestEnabled = !isIntegrationTest;
17+
OnStateEnterCounter.Clear();
18+
}
19+
20+
public static bool AllStatesEnteredMatch(List<ulong> clientIdsToCheck)
21+
{
22+
if (clientIdsToCheck.Contains(NetworkManager.ServerClientId))
23+
{
24+
clientIdsToCheck.Remove(NetworkManager.ServerClientId);
25+
}
26+
27+
if (!OnStateEnterCounter.ContainsKey(NetworkManager.ServerClientId))
28+
{
29+
Debug.Log($"Server has not entered into any states! OnStateEntered Entry Count ({OnStateEnterCounter.Count})");
30+
return false;
31+
}
32+
33+
var serverStates = OnStateEnterCounter[NetworkManager.ServerClientId];
34+
35+
foreach (var layerEntries in serverStates)
36+
{
37+
var layerIndex = layerEntries.Key;
38+
var layerStates = layerEntries.Value;
39+
if (layerStates.Count > 1)
40+
{
41+
Debug.Log($"Server layer ({layerIndex}) state was entered ({layerStates.Count}) times!");
42+
return false;
43+
}
44+
45+
foreach (var clientId in clientIdsToCheck)
46+
{
47+
if (!OnStateEnterCounter.ContainsKey(clientId))
48+
{
49+
Debug.Log($"Client-{clientId} never entered into any state for layer index ({layerIndex})!");
50+
return false;
51+
}
52+
var clientStates = OnStateEnterCounter[clientId];
53+
if (!clientStates.ContainsKey(layerIndex))
54+
{
55+
Debug.Log($"Client-{clientId} never layer ({layerIndex}) state!");
56+
return false;
57+
}
58+
var clientLayerStateEntries = clientStates[layerIndex];
59+
if (clientLayerStateEntries.Count > 1)
60+
{
61+
Debug.Log($"Client-{clientId} layer ({layerIndex}) state was entered ({layerStates.Count}) times!");
62+
return false;
63+
}
64+
// We should have only entered into the state once on the server
65+
// and all connected clients
66+
var serverAnimStateInfo = layerStates[0];
67+
var clientAnimStateInfo = clientLayerStateEntries[0];
68+
// We just need to make sure we are looking at the same state
69+
if (clientAnimStateInfo.fullPathHash != serverAnimStateInfo.fullPathHash)
70+
{
71+
Debug.Log($"Client-{clientId} full path hash ({clientAnimStateInfo.fullPathHash}) for layer ({layerIndex}) was not the same as the Server full path hash ({serverAnimStateInfo.fullPathHash})!");
72+
return false;
73+
}
74+
}
75+
}
76+
return true;
77+
}
78+
79+
public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
80+
{
81+
if (IsIntegrationTest)
82+
{
83+
var networkObject = animator.GetComponent<NetworkObject>();
84+
var localClientId = networkObject.NetworkManager.IsServer ? NetworkManager.ServerClientId : networkObject.NetworkManager.LocalClientId;
85+
if (!OnStateEnterCounter.ContainsKey(localClientId))
86+
{
87+
OnStateEnterCounter.Add(localClientId, new Dictionary<int, List<AnimatorStateInfo>>());
88+
}
89+
if (!OnStateEnterCounter[localClientId].ContainsKey(layerIndex))
90+
{
91+
OnStateEnterCounter[localClientId].Add(layerIndex, new List<AnimatorStateInfo>());
92+
}
93+
OnStateEnterCounter[localClientId][layerIndex].Add(stateInfo);
94+
}
95+
else if (IsManualTestEnabled)
96+
{
97+
Debug.Log($"[{layerIndex}][{stateInfo.shortNameHash}][{stateInfo.normalizedTime}][{animator.IsInTransition(layerIndex)}]");
98+
}
99+
}
100+
}
101+
}

testproject/Assets/Tests/Manual/NetworkAnimatorTests/CheckStateEnterCount.cs.meta

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

testproject/Assets/Tests/Manual/NetworkAnimatorTests/CubeAnimatorController.controller

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,18 @@ AnimatorState:
337337
m_MirrorParameter:
338338
m_CycleOffsetParameter:
339339
m_TimeParameter:
340+
--- !u!114 &-268161786856038416
341+
MonoBehaviour:
342+
m_ObjectHideFlags: 1
343+
m_CorrespondingSourceObject: {fileID: 0}
344+
m_PrefabInstance: {fileID: 0}
345+
m_PrefabAsset: {fileID: 0}
346+
m_GameObject: {fileID: 0}
347+
m_Enabled: 1
348+
m_EditorHideFlags: 0
349+
m_Script: {fileID: 11500000, guid: beb3702bd4c8d274e9dffe0c6467eafb, type: 3}
350+
m_Name:
351+
m_EditorClassIdentifier:
340352
--- !u!1107 &-108110249979471251
341353
AnimatorStateMachine:
342354
serializedVersion: 6
@@ -453,6 +465,18 @@ AnimatorController:
453465
m_IKPass: 0
454466
m_SyncedLayerAffectsTiming: 0
455467
m_Controller: {fileID: 9100000}
468+
--- !u!114 &252787195921886346
469+
MonoBehaviour:
470+
m_ObjectHideFlags: 1
471+
m_CorrespondingSourceObject: {fileID: 0}
472+
m_PrefabInstance: {fileID: 0}
473+
m_PrefabAsset: {fileID: 0}
474+
m_GameObject: {fileID: 0}
475+
m_Enabled: 1
476+
m_EditorHideFlags: 0
477+
m_Script: {fileID: 11500000, guid: beb3702bd4c8d274e9dffe0c6467eafb, type: 3}
478+
m_Name:
479+
m_EditorClassIdentifier:
456480
--- !u!1101 &1138737138882309440
457481
AnimatorStateTransition:
458482
m_ObjectHideFlags: 1
@@ -561,6 +585,7 @@ AnimatorState:
561585
- {fileID: 1138737138882309440}
562586
m_StateMachineBehaviours:
563587
- {fileID: 5559889042091692034}
588+
- {fileID: -268161786856038416}
564589
m_Position: {x: 50, y: 50, z: 0}
565590
m_IKOnFeet: 0
566591
m_WriteDefaultValues: 1
@@ -625,6 +650,7 @@ AnimatorState:
625650
- {fileID: 1830534497079063084}
626651
m_StateMachineBehaviours:
627652
- {fileID: 3735381422868909868}
653+
- {fileID: 252787195921886346}
628654
m_Position: {x: 50, y: 50, z: 0}
629655
m_IKOnFeet: 0
630656
m_WriteDefaultValues: 0

testproject/Assets/Tests/Manual/NetworkAnimatorTests/NetworkAnimatorTestPrefab.prefab

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -578,7 +578,7 @@ GameObject:
578578
- component: {fileID: 3604323723684300772}
579579
- component: {fileID: 6047057957339659638}
580580
- component: {fileID: 8104648428997222210}
581-
- component: {fileID: 5157980021080854601}
581+
- component: {fileID: 1245349943772079751}
582582
m_Layer: 0
583583
m_Name: NetworkAnimatedCube-Server
584584
m_TagString: Untagged
@@ -635,7 +635,7 @@ MonoBehaviour:
635635
m_Name:
636636
m_EditorClassIdentifier:
637637
TestIterations: 20
638-
--- !u!114 &5157980021080854601
638+
--- !u!114 &1245349943772079751
639639
MonoBehaviour:
640640
m_ObjectHideFlags: 0
641641
m_CorrespondingSourceObject: {fileID: 0}

0 commit comments

Comments
 (0)