Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Third Party Mirror networking instantiate objects

Discussion in 'Multiplayer' started by Zeepblok, Nov 11, 2020.

  1. Zeepblok

    Zeepblok

    Joined:
    Sep 26, 2015
    Posts:
    17
    Hi all,

    I have a little script to instantiate a bullet object. It goed perfect but it only works when your the server. The client gives the error NetworkServer is not active.. Seems logical to me since I'm using NetworkServer.spawn. The question is how do I make it so that the bullets also spawn on all clients and the server when your a client.

    This is the code
    Code (CSharp):
    1.             if (Input.GetMouseButtonDown(0))
    2.             {
    3.                 GameObject bulletClone = Instantiate(bullet, nozzle.transform.position, transform.rotation);
    4.                 bulletClone.GetComponent<Rigidbody>().velocity = nozzle.transform.forward * bulletSpeed;
    5.                 NetworkServer.Spawn(bulletClone);
    6.             }
     
  2. luke-unity

    luke-unity

    Joined:
    Sep 30, 2020
    Posts:
    306
    That's right in Mirror the server is in control of spawning objects. To have a client spawn an object you have to tell the server to do it. You can do that by using a command for instance. Something along the lines of:

    Code (CSharp):
    1. [Command]
    2. void CmdSpawnBullet()
    3. {
    4.     GameObject bulletClone = Instantiate(bullet, nozzle.transform.position, transform.rotation);
    5.     bulletClone.GetComponent<Rigidbody>().velocity = nozzle.transform.forward * bulletSpeed;
    6.     NetworkServer.Spawn(bulletClone);
    7. }
    8.  
    9. // Client code
    10. void Update(){
    11.     if (Input.GetMouseButtonDown(0))
    12.     {
    13.         CmdSpawnBullet();
    14.     }
    15. }
     
  3. Zeepblok

    Zeepblok

    Joined:
    Sep 26, 2015
    Posts:
    17
    Thank you :) thats what I was looking for. works like a charm
     
  4. Zelloxy

    Zelloxy

    Joined:
    Nov 15, 2013
    Posts:
    3
    I understand this code. But say I want to update bulletClone's properties AFTER it has been spawned on server from client? How do I do that?
     
  5. Lozzzyy

    Lozzzyy

    Joined:
    Jul 31, 2020
    Posts:
    9
    Just using ClientRpc/Commands like you would normally I suppose. What in particular do you want to change?
     
  6. e_Zinc

    e_Zinc

    Joined:
    Oct 31, 2019
    Posts:
    18
    If the client has authority:
    • Call functions on it and replicate properties to everyone else either with replicated variable callbacks or with the [Mirror.ClientRpc] tag (can exclude owner to avoid duplicate effects)
    If the client has no authority:
    • Call a function on the bullet with a [Mirror.Command] tag on it, and the server does the above