Mirror icon indicating copy to clipboard operation
Mirror copied to clipboard

SpawnHandler from NetworkClient.RegisterPrefab(prefab, SpawnHandler, UnspawnHandler); never gets called on client

Open spinaljack opened this issue 5 years ago • 16 comments

Describe the bug SpawnHandler from NetworkClient.RegisterPrefab(prefab, SpawnHandler, UnspawnHandler); never gets called on client (Also the docs are out of date; ClientScene.RegisterPrefab is obsolete)

How to reproduce the issue, step by step Copy the code for Setting Up a Game Object Pool with Custom Spawn Handlers in Mirror Docs here: https://mirror-networking.gitbook.io/docs/guides/gameobjects/custom-spawnfunctions#setting-up-a-game-object-pool-with-custom-spawn-handlers

  • Build or test multiplayer in the editor.
  • Spawn some objects on the host.
  • Unspawn some objects on the host.
  • Spawn the some more on the host.

Notice that the host is using the object pool but the client is not. Client instantiates new prefabs instead of using the pooled ones. Unspawned client objects remain in the scene and is not reused. The SpawnHandler function on the client never gets called, instead a new prefab is instatiated on the client.

Expected behavior Both client and host will use the object pool. SpawnHandler gets called on the client when the host spawns an object.

Screenshots Capture On the left you can see a small number of pooled coins on the host On the right you can see a long list of unpooled coins being generated on the client

Desktop (please complete the following information):

  • OS: windows 10
  • Build target: windows 64
  • Unity version: 2018.4.34f1
  • Mirror branch: Latest Unity Asset store version

spinaljack avatar May 04 '21 07:05 spinaljack

SpawnHandler never gets called on the client

spinaljack avatar May 04 '21 08:05 spinaljack

UnSpawn handler does get called on the client

spinaljack avatar May 04 '21 09:05 spinaljack

@MrGadget1024 or anyone who ever used spawn handlers: any thoughts?

miwarnec avatar Jul 09 '21 08:07 miwarnec

@MrGadget1024 or anyone who ever used spawn handlers: any thoughts?

I have a test case for this but it requires #2797 to be merged for it to work.

MrGadget1024 avatar Jul 10 '21 02:07 MrGadget1024

thanks for bug report, gonna take a look

miwarnec avatar Apr 04 '22 04:04 miwarnec

@spinaljack any chance you could share the exact code that you used?

miwarnec avatar Apr 04 '22 04:04 miwarnec

going through our pool example. the script has some compilation errors, need to update the example. probably easier to showcase with our tanks example too.

miwarnec avatar Apr 04 '22 04:04 miwarnec

noticed another issue when experimenting. build=server-only editor=client fire a few times build=stop server, then press start host editor=client

then fire again. now gets this error. looks like something isn't cleared when stopping. 2022-04-04_18-42-21@2x

miwarnec avatar Apr 04 '22 11:04 miwarnec

when starting for the first time (not like the above error), all works fine though.

build=host editor=client

firing uses the pool. which means that unspawn handler is called: https://gyazo.com/0dce45254a45fb28497c499f3fe414f2

miwarnec avatar Apr 04 '22 11:04 miwarnec

the only way to reproduce weird behaviour is when using NetworkClient.RegisterPrefab for a prefab that is still in NetworkManager's prefabs.

BUT this will show a big warning when attempting to do so: 2022-04-04_18-51-00@2x

in our PrefabPool example, this would keep prrojectiles in the scene forever.

miwarnec avatar Apr 04 '22 11:04 miwarnec

see branch: repro_2705

miwarnec avatar Apr 04 '22 11:04 miwarnec

@spinaljack is right, if prefab is registered twice (once in networkmanager prefabs, once with NetworkClient.RegisterPrefab) then it's spawned regularly, but it's despawned via unspawn handler.

there's a big warning explaining not to register twice, which is why this happens. but perhaps we should make this consistent anyway.

miwarnec avatar Apr 04 '22 11:04 miwarnec

SpawnPrefab looks for prefab first instead of looking for spawn handlers first: image

miwarnec avatar Apr 04 '22 12:04 miwarnec

fixed and added test to guarantee it never happens again. 2022-04-04_19-20-43@2x

miwarnec avatar Apr 04 '22 12:04 miwarnec

fixing the docs:

using UnityEngine;

namespace Mirror.Examples
{
    public class PrefabPool : MonoBehaviour
    {
        // singleton for easier access from other scripts
        public static PrefabPool singleton;

        [Header("Settings")]
        public GameObject prefab;

        [Header("Debug")]
        public int currentCount;
        public Pool<GameObject> pool;

        void Start()
        {
            InitializePool();
            singleton = this;
            NetworkClient.RegisterPrefab(prefab, SpawnHandler, UnspawnHandler);
        }

        // used by NetworkClient.RegisterPrefab
        GameObject SpawnHandler(SpawnMessage msg) => Get(msg.position, msg.rotation);

        // used by NetworkClient.RegisterPrefab
        void UnspawnHandler(GameObject spawned) => Return(spawned);

        void OnDestroy()
        {
            NetworkClient.UnregisterPrefab(prefab);
        }

        void InitializePool()
        {
            // create pool with generator function
            pool = new Pool<GameObject>(CreateNew, 5);
        }

        GameObject CreateNew()
        {
            // use this object as parent so that objects dont crowd hierarchy
            GameObject next = Instantiate(prefab, transform);
            next.name = $"{prefab.name}_pooled_{currentCount}";
            next.SetActive(false);
            currentCount++;
            return next;
        }

        // Used to take Object from Pool.
        // Should be used on server to get the next Object
        // Used on client by NetworkClient to spawn objects
        public GameObject Get(Vector3 position, Quaternion rotation)
        {
            GameObject next = pool.Get();

            // set position/rotation and set active
            next.transform.position = position;
            next.transform.rotation = rotation;
            next.SetActive(true);
            return next;
        }

        // Used to put object back into pool so they can b
        // Should be used on server after unspawning an object
        // Used on client by NetworkClient to unspawn objects
        public void Return(GameObject spawned)
        {
            // disable object
            spawned.SetActive(false);

            // add back to pool
            pool.Return(spawned);
        }
    }
}

miwarnec avatar Apr 04 '22 12:04 miwarnec

I am still getting the following error: Failed to spawn server object, did you forget to add it to the NetworkManager? assetId=339394605 netId=4 UnityEngine.Debug:LogError (object) Mirror.NetworkClient:SpawnPrefab (Mirror.SpawnMessage) (at Assets/Mirror/Core/NetworkClient.cs:1137) Mirror.NetworkClient:FindOrSpawnObject (Mirror.SpawnMessage,Mirror.NetworkIdentity&) (at Assets/Mirror/Core/NetworkClient.cs:1086) Mirror.NetworkClient:OnSpawn (Mirror.SpawnMessage) (at Assets/Mirror/Core/NetworkClient.cs:1323) Mirror.NetworkClient/<>c__DisplayClass53_01<Mirror.SpawnMessage>:<RegisterHandler>g__HandlerWrapped|0 (Mirror.NetworkConnection,Mirror.SpawnMessage) (at Assets/Mirror/Core/NetworkClient.cs:492) Mirror.NetworkMessages/<>c__DisplayClass10_02<Mirror.SpawnMessage, Mirror.NetworkConnection>:g__Wrapped|0 (Mirror.NetworkConnection,Mirror.SpawnMessage,int) (at Assets/Mirror/Core/NetworkMessages.cs:170) Mirror.NetworkMessages/<>c__DisplayClass9_02<Mirror.SpawnMessage, Mirror.NetworkConnection>:<WrapHandler>b__0 (Mirror.NetworkConnection,Mirror.NetworkReader,int) (at Assets/Mirror/Core/NetworkMessages.cs:152) Mirror.NetworkClient:UnpackAndInvoke (Mirror.NetworkReader,int) (at Assets/Mirror/Core/NetworkClient.cs:304) Mirror.NetworkClient:OnTransportData (System.ArraySegment1,int) (at Assets/Mirror/Core/NetworkClient.cs:372) kcp2k.KcpTransport:b__23_2 (System.ArraySegment1<byte>,kcp2k.KcpChannel) (at Assets/Mirror/Transports/KCP/MirrorTransport/KcpTransport.cs:107) kcp2k.KcpClient:<Connect>b__8_1 (System.ArraySegment1,kcp2k.KcpChannel) (at Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpClient.cs:70) kcp2k.KcpConnection:TickIncoming_Authenticated (uint) (at Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpConnection.cs:341) kcp2k.KcpConnection:TickIncoming () (at Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpConnection.cs:383) kcp2k.KcpClient:TickIncoming () (at Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpClient.cs:128) kcp2k.KcpTransport:ClientEarlyUpdate () (at Assets/Mirror/Transports/KCP/MirrorTransport/KcpTransport.cs:194) Mirror.NetworkClient:NetworkEarlyUpdate () (at Assets/Mirror/Core/NetworkClient.cs:1487) Mirror.NetworkLoop:NetworkEarlyUpdate () (at Assets/Mirror/Core/NetworkLoop.cs:179)

basuarya avatar Nov 22 '22 05:11 basuarya