This commit is contained in:
2025-11-13 17:40:28 +08:00
parent 962ab49609
commit 10156da245
5503 changed files with 805282 additions and 0 deletions

View File

@@ -0,0 +1,65 @@
using UnityEngine;
using Mirror;
using Mirror.Discovery;
using Cysharp.Threading.Tasks;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Tuan.GameFramework
{
public class AutoStart : MonoBehaviour
{
public NetworkManager networkManager;
public NetworkDiscovery networkDiscovery;
public float waitForHostTimeout = 1f;
private bool hostFound = false;
private async void Start()
{
networkDiscovery.OnServerFound.AddListener(OnServerFound);
await Connect();
}
private async UniTask Connect()
{
if (networkManager == null || networkDiscovery == null)
{
Debug.LogError("请确认 NetworkManager 和 NetworkDiscovery 已设置");
return;
}
hostFound = false;
networkDiscovery.StartDiscovery();
await UniTask.WaitForSeconds(1.1f);
if (!hostFound)
{
Debug.Log("未发现 Host自己成为 Host");
networkManager.StartHost();
networkDiscovery.AdvertiseServer();
}
}
private void OnServerFound(ServerResponse info)
{
if (hostFound) return;
hostFound = true;
Debug.Log($"发现 Host: {info.uri.Host}");
networkDiscovery.StopDiscovery();
networkManager.networkAddress = info.uri.Host;
networkManager.StartClient();
}
private void OnDestroy()
{
if (networkDiscovery != null)
networkDiscovery.OnServerFound.RemoveListener(OnServerFound);
}
}
}