Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Initialize Spawned object with data

Discussion in 'Netcode for GameObjects' started by SimoGecko, Sep 13, 2023.

  1. SimoGecko

    SimoGecko

    Joined:
    Sep 28, 2014
    Posts:
    13
    Hi, I'm spawning some object on the server and then propagating it to clients using NetworkObject.Spawn(). However, I would like to be able to set some properties for initialization and be able to retrieve them on the clients.

    Currently, I'm not aware of a way to make sure those properties are set on clients by the time OnNetworkSpawn() is called.
    Using both RPC or NetworkVariables there is no guarantee (I believe) that the messages will arrive on the client exactly in time for OnNetworkSpawn.

    My current work-around is to use a NetworkVariable which is set on the server. On Clients, during OnNetworkSpawn, I subscribe to OnValueChanged, and then once the message arrives I do my initialization there and enable the entity. This seems quite cumbersome. Is there a way to bundle information when spawning, or a guarantee that NetworkVariables set on the spawned instance on the server will be propagated on client by the time the objects spawn? Thanks
     
    lavagoatGG likes this.
  2. cerestorm

    cerestorm

    Joined:
    Apr 16, 2020
    Posts:
    598
    I'm sure you used to be able to do this if you set the values in the same frame as the Spawn call, I guess that's a thing of the past.

    You can instantiate a prefab, set the values, then call Spawn but you get annoying warnings doing this.

    Another thing to try is to untick Spawn With Observers on the prefab's NetworkObject and then call NetworkShow after setting the values. It looks like it works on clients but it won't work for the host.
     
    lavagoatGG likes this.
  3. SimoGecko

    SimoGecko

    Joined:
    Sep 28, 2014
    Posts:
    13
    Thank you for your reply. Are you saying that if I set a NetworkVariable on the server on the same frame I spawn and call NetworkObject.Spawn(), by the time I get the OnNetworkSpawn() callback on clients those network variables should be set as in the server?
     
  4. cerestorm

    cerestorm

    Joined:
    Apr 16, 2020
    Posts:
    598
    That used to be the way but doesn't seem to work now. The other two ways should work though, at least they did in a simple test.