Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Unity.Entities;
- using Unity.NetCode;
- using Unity.Networking.Transport;
- using UnityEngine;
- using UnityEngine.SceneManagement;
- public class NetworkManager : MonoBehaviour
- {
- public static NetworkManager Instance { get; private set; }
- public ushort Port = 7979;
- [SerializeField] private string gameSceneName = "World";
- void Awake()
- {
- if (Instance != null && Instance != this)
- {
- Destroy(gameObject);
- return;
- }
- Instance = this;
- DontDestroyOnLoad(gameObject);
- }
- public void StartServer(bool anyIpv4 = false)
- {
- var endpoint = anyIpv4
- ? NetworkEndpoint.AnyIpv4.WithPort(Port)
- : NetworkEndpoint.LoopbackIpv4.WithPort(Port);
- CleanupOldWorlds();
- var serverWorld = ClientServerBootstrap.CreateServerWorld("ServerWorld");
- var clientWorld = ClientServerBootstrap.CreateClientWorld("ClientWorld");
- World.DefaultGameObjectInjectionWorld = clientWorld;
- ScriptBehaviourUpdateOrder.AppendWorldToCurrentPlayerLoop(serverWorld);
- ScriptBehaviourUpdateOrder.AppendWorldToCurrentPlayerLoop(clientWorld);
- // listen
- var serverDriver = serverWorld.EntityManager
- .CreateEntityQuery(typeof(NetworkStreamDriver))
- .GetSingletonRW<NetworkStreamDriver>();
- serverDriver.ValueRW.Listen(endpoint);
- // client always connects loopback for same‑machine play
- var clientDriver = clientWorld.EntityManager
- .CreateEntityQuery(typeof(NetworkStreamDriver))
- .GetSingletonRW<NetworkStreamDriver>();
- clientDriver.ValueRW.Connect(clientWorld.EntityManager,
- NetworkEndpoint.LoopbackIpv4.WithPort(Port));
- SceneManager.LoadScene(gameSceneName, LoadSceneMode.Single);
- Debug.Log($"Server listening on {(anyIpv4 ? GetLocalIp() : "127.0.0.1")}:{Port}");
- }
- public void JoinServer(string ip, ushort port)
- {
- CleanupOldWorlds();
- var clientWorld = ClientServerBootstrap.CreateClientWorld("ClientWorld");
- World.DefaultGameObjectInjectionWorld = clientWorld;
- ScriptBehaviourUpdateOrder.AppendWorldToCurrentPlayerLoop(clientWorld);
- var endpoint = NetworkEndpoint.Parse(ip, port);
- var clientDriver = clientWorld.EntityManager
- .CreateEntityQuery(typeof(NetworkStreamDriver))
- .GetSingletonRW<NetworkStreamDriver>();
- clientDriver.ValueRW.Connect(clientWorld.EntityManager, endpoint);
- SceneManager.LoadScene(gameSceneName, LoadSceneMode.Single);
- }
- private void CleanupOldWorlds()
- {
- for (int i = World.All.Count - 1; i >= 0; i--)
- {
- var w = World.All[i];
- if ((w.Flags & (WorldFlags.Game | WorldFlags.GameServer)) != 0)
- w.Dispose();
- }
- }
- string GetLocalIp()
- {
- foreach (var ip in System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList)
- {
- if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
- return ip.ToString();
- }
- return "127.0.0.1";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment