Search Unity

Spawning objects from a non-player controlled object

Discussion in 'Multiplayer' started by Juzziee, Jan 27, 2019.

  1. Juzziee

    Juzziee

    Joined:
    Sep 29, 2014
    Posts:
    2
    Hey guys,

    I am working on my first networking game and running into a slight issue.
    I am trying to spawn objects from a non-player controlled object.

    Currently, I have the two players connecting to the server, where there is a 'chest'. When the player interacts with the chest, it should spawn an item outside the chest. Each chest will have their own separate items.

    When the host interacts with the chest, the item spawns for the host but not the connected client.
    When the client attempts to interact with the chest, I am told "Trying to send command for object without authority."

    My current chest script is as follow;

    Code (CSharp):
    1. public class Chest : Interactable {
    2.  
    3.     public GameObject Item;
    4.     public GameObject itemTop;
    5.     public Transform itemSpawn;
    6.     private Player _player;
    7.  
    8.     public override void Interact(GameObject player) {
    9.         _player = player.GetComponent<Player>();
    10.  
    11.         if (_player.holding == null) {
    12.             if (itemTop == null) {
    13.                 CmdSpawn();
    14.             } else {
    15.                 // Player picks up item
    16.                 _player.holding = itemTop;
    17.                 _player.holding.transform.parent = _player.holdingPosition;
    18.                 _player.holding.gameObject.transform.localPosition = Vector3.zero;
    19.                 itemTop = null;
    20.             }
    21.         } else {
    22.             // Place object at the tables spawn position
    23.             itemTop = _player.holding;
    24.             itemTop.transform.parent = this.gameObject.transform;
    25.             itemTop.transform.position = itemSpawn.position;
    26.             _player.holding = null;
    27.         }
    28.     }
    29.  
    30.     [Command]
    31.     void CmdSpawn() {
    32.         GameObject spawnItem;
    33.         spawnItem = Instantiate(Item, itemSpawn.position, Quaternion.identity);
    34.         Debug.Log("Spawning item");
    35.         NetworkServer.SpawnWithClientAuthority(spawnItem, this.gameObject);
    36.         itemTop = spawnItem;
    37.     }
    38. }
    Chest chest is has a network identity with Local Player Authority as do my players.

    Does anyone have any guidance for me to best spawn objects from the chest at both host and clients request?

    Thanks in advance!

    Edit: I should also mention that the Interacting class is inheriting NetworkBehaviour
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Send the Command on that client's Player GameObject instead of on the chest object, or use Unet Messages instead.