|
| 1 | +--- |
| 2 | +id: target-instance |
| 3 | +title: Use tags to run a player as a server, client, or host |
| 4 | +description: This example shows how you can use Netcode for GameObjects to run a Player as a server, client, or host in Multiplayer Play Mode. |
| 5 | +--- |
| 6 | + |
| 7 | +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](https://docs-multiplayer.unity3d.com/netcode/current/basics/networkobject/) (such as the **Player**). |
| 8 | + |
| 9 | +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](../dedicated-server/play-mode-dedicated-server.md). |
| 10 | + |
| 11 | +## Set a tag to server, client, or host in a script |
| 12 | + |
| 13 | +The following script uses the Netcode for GameObjects [NetworkManager](https://docs-multiplayer.unity3d.com/netcode/current/components/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. |
| 14 | + |
| 15 | +:::important |
| 16 | +This example uses the `Contains` method, which is case-sensitive by default. To make it case-insensitive, pass the `System.StringComparison.CurrentCultureIgnoreCase` method. |
| 17 | +::: |
| 18 | + |
| 19 | +:::note |
| 20 | +This example uses [Netcode for GameObjects](https://docs-multiplayer.unity3d.com/netcode/current/about/). |
| 21 | +::: |
| 22 | + |
| 23 | +```csharp |
| 24 | +using Unity.Netcode; |
| 25 | +using UnityEngine; |
| 26 | +using Unity.Multiplayer.Playmode; |
| 27 | + |
| 28 | +/// A MonoBehaviour to automatically start Netcode for GameObjects |
| 29 | +/// clients, hosts, and servers |
| 30 | +public class MppmConnect : MonoBehaviour |
| 31 | +{ |
| 32 | + void Start() |
| 33 | + { |
| 34 | + var mppmTag = CurrentPlayer.ReadOnlyTags(); |
| 35 | + var networkManager = NetworkManager.Singleton; |
| 36 | + if (mppmTag.Contains("Server")) |
| 37 | + { |
| 38 | + networkManager.StartServer(); |
| 39 | + } |
| 40 | + else if (mppmTag.Contains("Host")) |
| 41 | + { |
| 42 | + networkManager.StartHost(); |
| 43 | + } |
| 44 | + else if (mppmTag.Contains("Client")) |
| 45 | + { |
| 46 | + networkManager.StartClient(); |
| 47 | + } |
| 48 | + } |
| 49 | +} |
| 50 | +``` |
0 commit comments