Search code examples
unity-game-engineunity-networking

Unity UNet client authority


I'm making a multiplayer game and I'm trying to instantiate a new object on the client. The object should be controlled by that player alone.

I tried it by simply instantiating it on the client, and then spawning it:

public class Player : NetworkBehaviour
{
    [SerializeField]
    private Card _testCard;

    void Update()
    {
        if (!isLocalPlayer) return;

        if (Input.GetKeyDown(KeyCode.Space))
        {
            RaycastHit hit;
            if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
            {
                var card = Instantiate(_testCard);
                card.transform.position = hit.point;
                card.Name = "Test";
                NetworkServer.Spawn(card.gameObject);
                //or call this from a command, shown below
            }
        }
    }

    /*[Command]
    void CmdPlayTestCard(string name, Vector3 position)
    {
        var card = Instantiate(_testCard);
        card.transform.position = position;
        card.Name = name;
        NetworkServer.Spawn(card.gameObject);
    }*/
}

This spawns the object on the client, and it can be controlled by it, but doesn't spawn on the server.

I also did the same in a Command and then it is instantiated everywhere but the client can't controll it. The server can however control it.

What is the proper way of doing this? Creating an object that should be controlled by one of the players, rather than the server?

I tried googling it but couldn't find anything.

Thanks!


Solution

  • I found that this is comming in Unity 5.2, the current beta release notes list this as a feature: "Networking: Added support for client-side authority for non-player objects."

    So this will be coming in September for everyone.