Files
VR-WuKong/Assets/GameFramework/Runtime/Network/AutoStart.cs
2025-11-13 17:40:28 +08:00

65 lines
1.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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