100 lines
3.1 KiB
C#
100 lines
3.1 KiB
C#
using Cysharp.Threading.Tasks;
|
|
using Mirror;
|
|
using Mirror.Discovery;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
namespace Tuan.GameFramework
|
|
{
|
|
public class AutoStart : MonoBehaviour
|
|
{
|
|
public bool alwaysAutoStart = false;
|
|
public VRNetworkDiscovery networkDiscovery;
|
|
readonly Dictionary<long, ServerResponse> discoveredServers = new Dictionary<long, ServerResponse>();
|
|
public float waitForHostTimeout = 1f;
|
|
private async void Start()
|
|
{
|
|
// skips waiting for users to press ui button
|
|
if (alwaysAutoStart)
|
|
{
|
|
await Waiter();
|
|
}
|
|
}
|
|
|
|
public async UniTask Waiter()
|
|
{
|
|
discoveredServers.Clear();
|
|
networkDiscovery.StartDiscovery();
|
|
// we have set this as 3.1 seconds, default discovery scan is 3 seconds, allows some time if host and client are started at same time
|
|
await UniTask.WaitForSeconds(waitForHostTimeout);
|
|
if (discoveredServers == null || discoveredServers.Count <= 0)
|
|
{
|
|
Debug.Log("No Servers found, starting as Host.");
|
|
await UniTask.WaitForSeconds(0.1f);
|
|
discoveredServers.Clear();
|
|
VRNetworkManager.singleton.StartHost();
|
|
networkDiscovery.AdvertiseServer();
|
|
}
|
|
}
|
|
|
|
void Connect(ServerResponse info)
|
|
{
|
|
Debug.Log($"Connecting to: {info.uri.Host}");
|
|
networkDiscovery.StopDiscovery();
|
|
VRNetworkManager.singleton.StartClient(info.uri);
|
|
}
|
|
|
|
public void OnDiscoveredServer(ServerResponse info)
|
|
{
|
|
discoveredServers[info.serverId] = info;
|
|
Connect(info);
|
|
}
|
|
|
|
public void StartAsHost()
|
|
{
|
|
Debug.Log("Starting as host");
|
|
discoveredServers.Clear();
|
|
VRNetworkManager.singleton.StartHost();
|
|
networkDiscovery.AdvertiseServer();
|
|
|
|
}
|
|
|
|
public void StartAsServer()
|
|
{
|
|
Debug.Log("Starting as server");
|
|
discoveredServers.Clear();
|
|
// VRNetworkManager.singleton.onlineScene = SceneManager.GetActiveScene().name;
|
|
VRNetworkManager.singleton.StartServer();
|
|
networkDiscovery.AdvertiseServer();
|
|
|
|
}
|
|
|
|
public void StartAsClient()
|
|
{
|
|
Debug.Log("Starting as client.");
|
|
discoveredServers.Clear();
|
|
networkDiscovery.StartDiscovery();
|
|
}
|
|
|
|
public void Stop()
|
|
{
|
|
Debug.Log("Stopping");
|
|
// stop host if host mode
|
|
if (NetworkServer.active && NetworkClient.isConnected)
|
|
{
|
|
VRNetworkManager.singleton.StopHost();
|
|
}
|
|
// stop client if client-only
|
|
else if (NetworkClient.isConnected)
|
|
{
|
|
VRNetworkManager.singleton.StopClient();
|
|
}
|
|
// stop server if server-only
|
|
else if (NetworkServer.active)
|
|
{
|
|
VRNetworkManager.singleton.StopServer();
|
|
}
|
|
networkDiscovery.StopDiscovery();
|
|
}
|
|
}
|
|
} |