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); } } }