Search Unity

Spawn() and late joiners

Discussion in 'Netcode for GameObjects' started by Brunosly, Apr 24, 2023.

  1. Brunosly

    Brunosly

    Joined:
    Nov 8, 2012
    Posts:
    6
    So as far as I understood from the documentation, the function Spawn should make that all late joiners also instantiate the object. But currently I can only make it work for players already connected to the server.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using Unity.Netcode;
    5.  
    6. public class PrepareGameplay_Server : MonoBehaviour
    7. {
    8.     [HideInInspector] public int quantityOfRooms;
    9.     [HideInInspector] public int decksPerRoom;
    10.     [SerializeField] GameObject deckPrefab;
    11.  
    12.     void Start()
    13.     {
    14.         if (NetworkManager.Singleton.IsServer)
    15.         {
    16.             for (int i = 0; i < quantityOfRooms; i++)
    17.             {
    18.                 for (int j = 0; j < decksPerRoom; j++)
    19.                 {
    20.                     GameObject deck = Instantiate(deckPrefab);
    21.                     deck.transform.SetParent(this.transform);
    22.                     deck.GetComponent<Deck>().currentRoom.Value = i;
    23.                     deck.GetComponent<NetworkObject>().Spawn(true);
    24.                 }
    25.             }
    26.         }
    27.     }
    28. }
    29.  
    Am I doing something wrong here?
     
  2. fernando-a-cortez

    fernando-a-cortez

    Unity Technologies

    Joined:
    Dec 14, 2020
    Posts:
    11
    Hi,

    What jumps out at me is line 21 where you're modifying the parent of the GameObject prior to spawning the NetworkObject over the network.

    Modifications of a NetworkObject's parent should always go through the NetworkObject.TrySetParent API as detailed here: https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/networkobject-parenting. You would want to ensure that the GameObject that you're parenting the deck to is also a NetworkObject, and that you perform this operation after spawning the NetworkObject.

    Assuming the deck NetworkObject is registered under your NetworkManager's list of NetworkPrefabs, the rest should still work, and Netcode will automatically synchronize the server's NetworkObjects to the late-joining client.

    Are there any warnings or logs produced on the late-joining client you're able to share? I hope that helps!