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

How do I properly adjust spawned network prefabs

Discussion in 'Netcode for GameObjects' started by YurySedyakin, Jul 5, 2023.

  1. YurySedyakin

    YurySedyakin

    Joined:
    Jul 25, 2018
    Posts:
    61
    Hello all,
    Here's my problem: I spawn a network object from a prefab, it has some network behaviours with network variables. Upon spawning the prefab I want to adjust values of the network variables for this particular instance that I just spawned.
    I tried setting values before calling NetworkObject.Spawn() - this gives me a warning:

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

    Ok then, I decided to set the values of network variables after the NetworkObject.Spawn() call. This works, but on the clients (when the spawned object gets spawned there) I get a few frames of invalid values in my network variables. So the question - is there a way to adjust a network object upon spawning before syncing it to the clients?
     
  2. lavagoatGG

    lavagoatGG

    Joined:
    Apr 16, 2022
    Posts:
    218
    A solution I can think of is to spawn the networkObject only on server and hidden from clients, change the values and then show it to the clients
     
  3. RikuTheFuffs-U

    RikuTheFuffs-U

    Unity Technologies

    Joined:
    Feb 20, 2020
    Posts:
    426
    Hi @YurySedyakin , there's an example on how to initialize clients upon spawn here, using OnNetworkSpawn. It's not exactly what you're asking for, but should give you an idea of the workflow.

    As a side note:

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

    is an unharmful error, and if your purpose is to modify a variable before the object spawns, that's the right workflow!
     
    YurySedyakin likes this.