Passing additional parameters when spawning network objects

I’m struggling to find a solid answer on what seems should be a pretty standard use-case: spawning a network object with particular params specified by the server.

I expected to be able to :

  1. Instantiate (on server)
  2. Set network variables
  3. Spawn (I hoped spawning would propagate the net variables)

However, in doing this I get the warning:

NetworkVariable is written to, but doesn’t know its NetworkBehaviour yet. Are you modifying a NetworkVariable before the NetworkObject is spawned?

Is there any way to do this cleanly?

I can think of some workarounds; however, they all seem pretty painful:

Send the initial params from the server OnNetworkSpawn:

  1. Spawn the object in a “hidden” state
  2. Set the initial param values in “OnNetworkSpawn” on the server, and also set a “hasBeenInitiailsed” flag
  3. Upon this flag being set, show the object on the client

…Presumably this is likely to result in object appearing probably a few frames late :frowning:

Prespawn the object, and then use an RPC to enable it

Keep a pool of pre-spawned objects that are somehow hidden. Then, instead of needing to spawn an object, the server just switches one on, either via a network variable, or an RPC.

This seems like a lot of unnecessary work, particularly if pooling is not actually required for any other reason (e.g. it’s an object that is spawned rarely).

Any thoughts?

Yes, it’s been detailed by a dev here: How to disable "NetworkVariable is written to, but doesn't know its NetworkBehaviour yet" LogWarning? · Issue #2561 · Unity-Technologies/com.unity.netcode.gameobjects · GitHub

No workarounds necessary.

Do keep in mind that you can also use RPCs to send one-off parameters. I see it a lot where NetworkVariable are used where they aren’t needed because either they never change once initially set and/or there is no need to sync the value(s) for late-joining clients.

Great thanks!

For anyone else reading this thread, the TL;DR:

You can set it in OnNetworkSpawn (locally on the server host), and it’s then guaranteed to be set for clients when it’s later spawned locally for each client.

It would be great if it mentioned this in the documentation…