Skip to content

Commit

Permalink
fix: network objects not destroyed on server stop (#468)
Browse files Browse the repository at this point in the history
* bug: network objects not destroyed on server stop

* hook Server.Stopped and loop through Spawned to Destroy all objects

* no need to call Client.Update() manually

* fix failing test. setup was not waiting for client to spawn player
  • Loading branch information
uweeby committed Dec 19, 2020
1 parent 3fd751a commit abf5f2f
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
10 changes: 10 additions & 0 deletions Assets/Mirror/Runtime/ServerObjectManager.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Mirror.RemoteCalls;
using UnityEngine;

Expand Down Expand Up @@ -32,6 +33,7 @@ public void Start()
{
server.Started.AddListener(SpawnOrActivate);
server.Authenticated.AddListener(OnAuthenticated);
server.Stopped.AddListener(OnServerStopped);
networkSceneManager.ServerChangeScene.AddListener(OnServerChangeScene);
networkSceneManager.ServerSceneChanged.AddListener(OnServerSceneChanged);
}
Expand Down Expand Up @@ -81,6 +83,14 @@ void OnAuthenticated(INetworkConnection connection)
RegisterMessageHandlers(connection);
}

void OnServerStopped()
{
foreach (NetworkIdentity obj in server.Spawned.Values.Reverse())
{
DestroyObject(obj, true);
}
}

void OnServerChangeScene(string scenePath, SceneOperation sceneOperation)
{
SetAllClientsNotReady();
Expand Down
3 changes: 2 additions & 1 deletion Assets/Tests/Runtime/HostSetup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ public class HostSetup<T> where T : NetworkBehaviour
serverObjectManager.AddPlayerForConnection(server.LocalConnection, playerGO);
client.Update();
// wait for client to spawn it
await AsyncUtil.WaitUntilWithTimeout(() => client.Connection.Identity != null);
});


Expand Down
16 changes: 16 additions & 0 deletions Assets/Tests/Runtime/ServerObjectManagerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,22 @@ public void UnSpawn()
// it should have been marked for reset now
Assert.That(identity.NetId, Is.Zero);
}

[UnityTest]
public IEnumerator DestroyAllSpawnedOnStopTest() => UniTask.ToCoroutine(async () =>
{
GameObject spawnTestObj = new GameObject("testObj", typeof(NetworkIdentity));
serverObjectManager.Spawn(spawnTestObj);
//1 is the player. should be 2 at this point
Assert.That(server.Spawned.Count, Is.GreaterThan(1));
server.Disconnect();
await AsyncUtil.WaitUntilWithTimeout(() => !server.Active);
Assert.That(server.Spawned.Count, Is.EqualTo(0));
});
}

public class ServerObjectManagerTest : ClientServerSetup<MockComponent>
Expand Down

0 comments on commit abf5f2f

Please sign in to comment.