Skip to content

Commit c79b7eb

Browse files
fix: respawn hybrid NetworkObject on NetworkShow after NetworkHide (#4236)
* fix: respawn hybrid NetworkObject on NetworkShow after NetworkHide On a client, despawning a hybrid NetworkObject leaves its GameObject to N4E, and NetworkHide does not make the ghost irrelevant, so the instance survives. Its pending ghost spawn entry was consumed on first spawn, so the CreateObjectMessage sent by NetworkShow waited for a ghost spawn that never came. The client now re-registers the surviving instance as a pending ghost spawn; NetworkObject.OnDestroy already drops the entry if N4E later destroys it. * fix: keep a re-shown hybrid instance usable after NetworkHide The despawn on NetworkHide marks the instance and its NetworkBehaviours as destroying, which stuck once the instance survived, so AttachableBehaviour could no longer detach on the client. The surviving instance now clears that flag. A retained child that NGO parented is no longer a root GameObject, so NetworkShow threw in MoveGameObjectToScene. Only root instances are moved into the active scene.
1 parent b0693ab commit c79b7eb

6 files changed

Lines changed: 190 additions & 4 deletions

File tree

‎com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -702,6 +702,14 @@ internal void SetIsDestroying()
702702
IsDestroying = true;
703703
}
704704

705+
/// <summary>
706+
/// Invoked by <see cref="NetworkObject.ResetIsDestroying"/>.
707+
/// </summary>
708+
internal void ResetIsDestroying()
709+
{
710+
IsDestroying = false;
711+
}
712+
705713
/// <summary>
706714
/// Updates properties with network session related
707715
/// dependencies such as a NetworkObject's spawned

‎com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1953,14 +1953,29 @@ internal void SetIsDestroying()
19531953
{
19541954
// Tell the childBehaviour that this NetworkObject is being destroyed.
19551955
// Keeping the property a private set to assure this is
1956-
// the only way it can be set as it should never be reset
1957-
// back to false once invoked.
1956+
// the only way it can be set. Only a hybrid instance that
1957+
// its ghost keeps alive resets it (ResetIsDestroying).
19581958
childBehaviour?.SetIsDestroying();
19591959
}
19601960
}
19611961
IsDestroying = true;
19621962
}
19631963

1964+
/// <summary>
1965+
/// Clears the despawning flag of a hybrid instance that its ghost keeps alive, and of its child NetworkBehaviours.
1966+
/// </summary>
1967+
internal void ResetIsDestroying()
1968+
{
1969+
if (ChildNetworkBehaviours != null)
1970+
{
1971+
foreach (var childBehaviour in ChildNetworkBehaviours.Values)
1972+
{
1973+
childBehaviour?.ResetIsDestroying();
1974+
}
1975+
}
1976+
IsDestroying = false;
1977+
}
1978+
19641979
private void OnDestroy()
19651980
{
19661981
SceneManager.activeSceneChanged -= CurrentlyActiveSceneChanged;

‎com.unity.netcode.gameobjects/Runtime/Spawning/GhostSpawnManager.cs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,11 @@ internal bool TryGetGhostNetworkObjectForSpawn(NetworkObject.SerializedObject se
115115

116116
// TODO-UNIFIED: We need a better way to preserve any hybrid instances pending NGO spawn.
117117
// NOTE: We might be able to use the NetworkSceneHandle to get the associated local scene handle to which we can use to get the targeted scene.
118-
UnityEngine.SceneManagement.SceneManager.MoveGameObjectToScene(networkObject.gameObject, UnityEngine.SceneManagement.SceneManager.GetActiveScene());
118+
// A child kept alive by its ghost (NetworkHide) is still parented and stays in its parent's scene.
119+
if (networkObject.transform.parent == null)
120+
{
121+
UnityEngine.SceneManagement.SceneManager.MoveGameObjectToScene(networkObject.gameObject, UnityEngine.SceneManagement.SceneManager.GetActiveScene());
122+
}
119123
return true;
120124
}
121125

‎com.unity.netcode.gameobjects/Runtime/Spawning/NetworkSpawnManager.cs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1958,7 +1958,12 @@ internal void OnDespawnObject([NotNull] NetworkObject networkObject, bool destro
19581958
// Unified netcode handles destroying the instance of the object on the non-authority side when the object has a ghost representation.
19591959
if (destroyGameObject && networkObject.HasGhost && !NetworkManager.IsServer)
19601960
{
1961-
// exit early
1961+
// A NetworkHide leaves the ghost alive, so the instance waits for a later NetworkShow (removed again if N4E destroys it).
1962+
if (networkObject && NetworkManager.IsConnectedClient && !NetworkManager.ShutdownInProgress)
1963+
{
1964+
networkObject.ResetIsDestroying();
1965+
GhostSpawnManager.RegisterGhostPendingSpawn(networkObject, networkObject.NetworkObjectId);
1966+
}
19621967
return;
19631968
}
19641969
#endif
Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
#if UNIFIED_NETCODE
2+
using System;
3+
using System.Collections;
4+
using NUnit.Framework;
5+
using Unity.Netcode.Components;
6+
using Unity.Netcode.TestHelpers.Runtime;
7+
using UnityEngine;
8+
using UnityEngine.TestTools;
9+
10+
namespace Unity.Netcode.RuntimeTests
11+
{
12+
/// <summary>
13+
/// Validates that hiding and then showing a spawned hybrid instance respawns it on the client.
14+
/// </summary>
15+
[TestFixture(HostOrServer.UnifiedHost)]
16+
[TestFixture(HostOrServer.UnifiedServer)]
17+
internal class HybridNetworkShowHideTests : NetcodeIntegrationTest
18+
{
19+
protected override int NumberOfClients => 1;
20+
21+
private GameObject m_HybridPrefab;
22+
private GameObject m_AttachablePrefab;
23+
private GameObject m_AttachableNodePrefab;
24+
private ulong m_NetworkObjectId;
25+
26+
public HybridNetworkShowHideTests(HostOrServer hostOrServer) : base(hostOrServer) { }
27+
28+
protected override bool UseUnifiedTests()
29+
{
30+
return true;
31+
}
32+
33+
protected override void OnServerAndClientsCreated()
34+
{
35+
m_HybridPrefab = CreateNetworkObjectPrefab("HybridShowHide");
36+
m_AttachablePrefab = CreateNetworkObjectPrefab("HybridAttachable");
37+
var attachableChild = new GameObject("AttachableChild");
38+
attachableChild.transform.parent = m_AttachablePrefab.transform;
39+
attachableChild.AddComponent<AttachableBehaviour>();
40+
m_AttachableNodePrefab = CreateNetworkObjectPrefab("HybridAttachableNode");
41+
var nodeChild = new GameObject("NodeChild");
42+
nodeChild.transform.parent = m_AttachableNodePrefab.transform;
43+
nodeChild.AddComponent<AttachableNode>();
44+
base.OnServerAndClientsCreated();
45+
}
46+
47+
private bool IsSpawnedOnClient()
48+
{
49+
return GetNonAuthorityNetworkManager().SpawnManager.SpawnedObjects.ContainsKey(m_NetworkObjectId);
50+
}
51+
52+
private IEnumerator SpawnOnAll(GameObject prefab, Action<NetworkObject> onSpawned)
53+
{
54+
var authorityInstance = SpawnObject(prefab, GetAuthorityNetworkManager()).GetComponent<NetworkObject>();
55+
yield return WaitForSpawnedOnAllOrTimeOut(authorityInstance);
56+
AssertOnTimeout($"[Setup] {authorityInstance.name} was not spawned on all instances!");
57+
onSpawned(authorityInstance);
58+
}
59+
60+
private IEnumerator HideThenShow(NetworkObject authorityInstance, string context)
61+
{
62+
var nonAuthority = GetNonAuthorityNetworkManager();
63+
m_NetworkObjectId = authorityInstance.NetworkObjectId;
64+
authorityInstance.NetworkHide(nonAuthority.LocalClientId);
65+
yield return WaitForConditionOrTimeOut(() => !IsSpawnedOnClient());
66+
AssertOnTimeout($"[{context}] {authorityInstance.name} was not despawned on Client-{nonAuthority.LocalClientId}!");
67+
68+
authorityInstance.NetworkShow(nonAuthority.LocalClientId);
69+
yield return WaitForConditionOrTimeOut(IsSpawnedOnClient);
70+
AssertOnTimeout($"[{context}] {authorityInstance.name} was not respawned on Client-{nonAuthority.LocalClientId}!");
71+
}
72+
73+
[UnityTest]
74+
public IEnumerator HideThenShowRespawnsOnClient()
75+
{
76+
var nonAuthority = GetNonAuthorityNetworkManager();
77+
NetworkObject authorityInstance = null;
78+
yield return SpawnOnAll(m_HybridPrefab, spawned => authorityInstance = spawned);
79+
var clientInstance = nonAuthority.SpawnManager.SpawnedObjects[authorityInstance.NetworkObjectId];
80+
81+
// A second cycle shows the respawned instance can be hidden and shown again.
82+
for (int i = 0; i < 2; i++)
83+
{
84+
yield return HideThenShow(authorityInstance, $"Cycle {i}");
85+
Assert.AreSame(clientInstance, nonAuthority.SpawnManager.SpawnedObjects[m_NetworkObjectId], $"[Cycle {i}] Client-{nonAuthority.LocalClientId} did not respawn the instance its ghost kept alive!");
86+
}
87+
}
88+
89+
[UnityTest]
90+
public IEnumerator HideThenShowParentedChild()
91+
{
92+
var nonAuthority = GetNonAuthorityNetworkManager();
93+
NetworkObject parent = null;
94+
NetworkObject child = null;
95+
yield return SpawnOnAll(m_HybridPrefab, spawned => parent = spawned);
96+
yield return SpawnOnAll(m_HybridPrefab, spawned => child = spawned);
97+
var clientParent = nonAuthority.SpawnManager.SpawnedObjects[parent.NetworkObjectId].transform;
98+
var clientChild = nonAuthority.SpawnManager.SpawnedObjects[child.NetworkObjectId].transform;
99+
Assert.IsTrue(child.TrySetParent(parent, false), $"{nameof(NetworkObject.TrySetParent)} failed!");
100+
yield return WaitForConditionOrTimeOut(() => clientChild.parent == clientParent);
101+
AssertOnTimeout($"[Setup] {child.name} was not parented on Client-{nonAuthority.LocalClientId}!");
102+
103+
yield return HideThenShow(child, "Parented");
104+
Assert.AreSame(clientParent, clientChild.parent, $"Client-{nonAuthority.LocalClientId} did not keep {child.name} parented!");
105+
}
106+
107+
[UnityTest]
108+
public IEnumerator HideThenShowThenAttachAndDetach()
109+
{
110+
var nonAuthority = GetNonAuthorityNetworkManager();
111+
NetworkObject source = null;
112+
NetworkObject node = null;
113+
yield return SpawnOnAll(m_AttachablePrefab, spawned => source = spawned);
114+
yield return SpawnOnAll(m_AttachableNodePrefab, spawned => node = spawned);
115+
yield return HideThenShow(source, "Attachable");
116+
117+
var clientSource = nonAuthority.SpawnManager.SpawnedObjects[source.NetworkObjectId].transform;
118+
var clientAttachable = clientSource.GetComponentInChildren<AttachableBehaviour>().transform;
119+
var clientNode = nonAuthority.SpawnManager.SpawnedObjects[node.NetworkObjectId].GetComponentInChildren<AttachableNode>().transform;
120+
var attachable = source.GetComponentInChildren<AttachableBehaviour>();
121+
122+
attachable.Attach(node.GetComponentInChildren<AttachableNode>());
123+
yield return WaitForConditionOrTimeOut(() => clientAttachable.parent == clientNode);
124+
AssertOnTimeout($"Client-{nonAuthority.LocalClientId} did not attach {clientAttachable.name}!");
125+
126+
attachable.Detach();
127+
yield return WaitForConditionOrTimeOut(() => clientAttachable.parent == clientSource);
128+
AssertOnTimeout($"Client-{nonAuthority.LocalClientId} did not detach {clientAttachable.name}!");
129+
}
130+
131+
[UnityTest]
132+
public IEnumerator DespawnWhileHiddenReleasesClientInstance()
133+
{
134+
var nonAuthority = GetNonAuthorityNetworkManager();
135+
NetworkObject authorityInstance = null;
136+
yield return SpawnOnAll(m_HybridPrefab, spawned => authorityInstance = spawned);
137+
m_NetworkObjectId = authorityInstance.NetworkObjectId;
138+
var clientInstance = nonAuthority.SpawnManager.SpawnedObjects[m_NetworkObjectId];
139+
140+
authorityInstance.NetworkHide(nonAuthority.LocalClientId);
141+
yield return WaitForConditionOrTimeOut(() => !IsSpawnedOnClient());
142+
AssertOnTimeout($"[Setup] {authorityInstance.name} was not despawned on Client-{nonAuthority.LocalClientId}!");
143+
Assert.IsTrue(nonAuthority.SpawnManager.GhostSpawnManager.IsGhostPendingSpawn(m_NetworkObjectId), $"Client-{nonAuthority.LocalClientId} is not holding the hidden instance for a later show!");
144+
145+
authorityInstance.Despawn();
146+
yield return WaitForConditionOrTimeOut(() => clientInstance == null);
147+
AssertOnTimeout($"N4E did not destroy the hidden instance on Client-{nonAuthority.LocalClientId}!");
148+
Assert.IsFalse(nonAuthority.SpawnManager.GhostSpawnManager.IsGhostPendingSpawn(m_NetworkObjectId), $"Client-{nonAuthority.LocalClientId} still holds the destroyed instance as pending!");
149+
}
150+
}
151+
}
152+
#endif

‎com.unity.netcode.gameobjects/Tests/Runtime/NetworkObject/HybridNetworkShowHideTests.cs.meta‎

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

0 commit comments

Comments
 (0)