UnityScripterAI
Discord ↗
Link Copied to Clipboard
×
"Multiplayer network"
using UnityEngine; using UnityEngine.Networking; public class CustomNetworkManager : NetworkManager { // Start is called before the first frame update void Start() { // Set the network address and port networkAddress = "localhost"; networkPort = 7777; } // Update is called once per frame void Update() { // Check if the server is active and if the client is not connected if (!NetworkServer.active && !NetworkClient.isConnected) { // Start the server if the "S" key is pressed if (Input.GetKeyDown(KeyCode.S)) { StartServer(); } // Start the client if the "C" key is pressed if (Input.GetKeyDown(KeyCode.C)) { StartClient(); } // Start the host if the "H" key is pressed if (Input.GetKeyDown(KeyCode.H)) { StartHost(); } } } public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId) { // Instantiate the player prefab GameObject player = Instantiate(playerPrefab, Vector3.zero, Quaternion.identity); // Spawn the player on the network NetworkServer.AddPlayerForConnection(conn, player, playerControllerId); } public override void OnServerDisconnect(NetworkConnection conn) { // Destroy the player object associated with the disconnected client NetworkServer.DestroyPlayersForConnection(conn); // Call the base functionality for handling server disconnects base.OnServerDisconnect(conn); } }