Use tags to run a player as a server, client, or host
This example explains how to target tags in your game scripts with CurrentPlayer.ReadOnlyTags()
. You can place these scripts where you want, but you must attach the scripts to a NetworkObject (such as the Player).
You can also use the dedicated server package to set a tag to server, client, or host. For more information, refer to Use Multiplayer Play Mode with a Dedicated Server.
Set a tag to server, client, or host in a script
The following script uses the Netcode for GameObjects NetworkManager to automatically connect the Virtual Player as a server, client, or host based on their tag. A Player with the Server
tag automatically runs as a server, and a Player with the Client
tag automatically runs as a client.
This example uses the Contains
method, which is case-sensitive by default. To make it case-insensitive, pass the System.StringComparison.CurrentCultureIgnoreCase
method.
This example uses Netcode for GameObjects.
using Unity.Netcode;
using UnityEngine;
using Unity.Multiplayer.Playmode;
/// A MonoBehaviour to automatically start Netcode for GameObjects
/// clients, hosts, and servers
public class MppmConnect : MonoBehaviour
{
void Start()
{
var mppmTag = CurrentPlayer.ReadOnlyTags();
var networkManager = NetworkManager.Singleton;
if (mppmTag.Contains("Server"))
{
networkManager.StartServer();
}
else if (mppmTag.Contains("Host"))
{
networkManager.StartHost();
}
else if (mppmTag.Contains("Client"))
{
networkManager.StartClient();
}
}
}