Search Unity

[SOLVED] How to spawn objects on the server?

Discussion in 'Multiplayer' started by BrunoPuccio, Jan 27, 2018.

  1. BrunoPuccio

    BrunoPuccio

    Joined:
    Dec 13, 2017
    Posts:
    22
    i have a game where 2 players can join, kill zombies and pickup guns, but my question is, How should i spawn the enemies?
    i want ONLY the host to have control about the spawning of items and zombies, what i mean is, i want to have a script that spawns zombies over time but i dont want them to spawn twice as fast when i have 2 players on the scene

    by far i have this

    [ClientRpc]
    void RpcSpawn()
    {
    for (int i = 0; i < spawnPoints.Length; i++)
    {
    spawned = (GameObject)Instantiate(items[Random.Range(0, items.Length)], spawnPoints.transform.position, Quaternion.identity);
    NetworkServer.Spawn(spawned);
    }
    }

    void Start()
    {
    spawnPoints = GameObject.FindGameObjectsWithTag("ItemSpawner");
    if (!isServer)
    return;
    RpcSpawn();
    }

    but it still called twice when the other client connects, and when you connect to a server where the items have already spawned u dont see them at all


    Edit:
    i managed to make this work, it is not the best way but it works so i am ok with it, first i had to put all the prefabs in the networkmanager list and then

    Code (CSharp):
    1. public GameObject item;
    2.     public Transform position;
    3.  
    4.     void Start()
    5.     {
    6.         GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
    7.         if (isServer && players.Length==1)
    8.         {
    9.             ServerSpawn();
    10.         }
    11.     }
    12.  
    13.     [Server]
    14.     void ServerSpawn()
    15.     {
    16.         var spawned = (GameObject)Instantiate(item, position.position, Quaternion.identity);
    17.         NetworkServer.Spawn(spawned);
    18.     }
    i only wanted the first player to spawn items when he spawns, that is why i made an array of players and check if this was the first one
     
    Last edited: Jan 28, 2018