Unity Mirror - Authority

Unity Mirror - Authority

Unity Mirror - Authority

Network Authority

Authority is the way of determining who owns an object and who has control over it.

Server Authority

Server authority means the server has control over an object. By default, the server has authority over an object. This means the server will manage collectible items, moving platforms, AI characters, and other non-player network objects.

Client Authority

Client authority means the client has control over an object.

When a client has authority over an object, it can call Commands and the object will be automatically destroyed when the client disconnects.

Even when a client has authority over an object, the server still controls the SyncVar and other serialization features. In order to synchronize with other clients, a component will still need to call Commands to update the state on the server.

How is authority assigned?

By default, the server has authority over all objects. The server can grant authority to objects that clients need to control, such as player objects.

If you create a player object using NetworkServer.AddPlayerForConnection, authority will be granted automatically.

Using NetworkServer.Spawn

You can assign authority to a client when an object is spawned. To do this, you must pass the connection when issuing the spawn command.

GameObject go = Instantiate(prefab);

NetworkServer.Spawn(go, connectionToClient);

Using identity.AssignClientAuthority

You can assign authority to a client at any time by using AssignClientAuthority. You do this by calling AssignClientAuthority on the object you want to grant authority to.

identity.AssignClientAuthority(conn);

You might want to do this when a player picks up an item.

// Command on the player object

void CmdPickupItem(NetworkIdentity item)

{

    item.AssignClientAuthority(connectionToClient); 

}

How to remove authority

You can remove client authority from an object by using identity.RemoveClientAuthority.

identity.RemoveClientAuthority();

Authority cannot be removed from the player object. Instead, you will need to replace the player object using NetworkServer.ReplacePlayerForConnection.

About Authority

When authority is granted to or removed from an object, a notification message is sent to the client. This causes the OnStartAuthority or OnStopAuthority functions to be called.

Checking Authority

On the Client Side

The identity.isOwned property can be used to check if the local player has authority over an object.

On the Server Side

The identity.connectionToClient property can be checked to see which client has authority over an object. If it is null, it indicates the server has authority.