Search Unity

Resolved How can I call a function when all NetworkObjects are spawned on a client?

Discussion in 'Netcode for GameObjects' started by RattusMakeGame, Feb 22, 2023.

  1. RattusMakeGame

    RattusMakeGame

    Joined:
    Feb 19, 2023
    Posts:
    3
    Whenever a client joins, I'm trying to have an in-scene-placed network object access data from each player object for them. When the function is called using OnNetworkSpawn(), not all player objects are spawned in for that client yet and I can't find a way to call the function when they all are.

    Code (CSharp):
    1. public override void OnNetworkSpawn()
    2.     {
    3.         if(IsClient)
    4.         {
    5.             foreach(GameObject newObj in GameObject.FindGameObjectsWithTag("PM"))
    6.             {
    7.                 Debug.Log("Found object.");
    8.             }
    9.         }
    10.     }
    The above code only logs once on the client despite there being more network objects with the tag "PM" in the scene. Thank you :)
     
  2. RikuTheFuffs-U

    RikuTheFuffs-U

    Unity Technologies

    Joined:
    Feb 20, 2020
    Posts:
    440
    Hi @RattusMakeGame , if the server knows when all the players are connected, it can send a ClientRPC so all players do what they need to do
     
  3. RattusMakeGame

    RattusMakeGame

    Joined:
    Feb 19, 2023
    Posts:
    3
    I should have mentioned that the goal was to know when all player objects are spawned on the client-side even when joining in the middle of a session. Luckily, I found a solution but I appreciate the help :)

    The solution basically involved having the server hold a count of all players and having the client wait to make sure the count was greater than 0, then count all the player objects repeatedly in update using a tag and FindGameObjectsWithTag and execute the code once when they are equal.

    If there is a more efficient way to do this I would be glad to hear, but it works well enough for now.
     
    RikuTheFuffs-U likes this.