您最多选择25个主题
主题必须以中文或者字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
97 行
2.9 KiB
97 行
2.9 KiB
using System;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Unity.Cn.Multiverse;
|
|
using UnityEngine;
|
|
using UnityEngine.TextCore.Text;
|
|
|
|
namespace Unity.MegaCity.Gameplay
|
|
{
|
|
public class MultiverseSDKWrapper
|
|
{
|
|
private static MultiverseSDKWrapper _instance;
|
|
private MultiverseSdk m_Multiverse = null;
|
|
private CancellationTokenSource cancellationTokenSource = null;
|
|
|
|
// Private constructor prevents instantiation from other classes.
|
|
private MultiverseSDKWrapper() { }
|
|
|
|
public static MultiverseSDKWrapper Instance
|
|
{
|
|
get
|
|
{
|
|
if (_instance == null)
|
|
{
|
|
_instance = new MultiverseSDKWrapper();
|
|
}
|
|
return _instance;
|
|
}
|
|
}
|
|
|
|
public async void StartMultiverse()
|
|
{
|
|
// init multiverse
|
|
m_Multiverse = await MultiverseSdk.CreateInstance();
|
|
if (m_Multiverse == null)
|
|
{
|
|
Debug.LogError($"MultiverseSdk.CreateInstance() failed");
|
|
Application.Quit();
|
|
return;
|
|
}
|
|
Debug.Log("Multiverse is created");
|
|
}
|
|
|
|
public async void ReadyMultiverse()
|
|
{
|
|
// wait until multiverse created
|
|
while(m_Multiverse == null)
|
|
{
|
|
Debug.Log("m_Multiverse is null");
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
bool ok = await m_Multiverse.Ready();
|
|
if (!ok)
|
|
{
|
|
Debug.LogError("m_Multiverse.Ready() failed");
|
|
Application.Quit();
|
|
return;
|
|
}
|
|
|
|
var gs = await m_Multiverse.GameServer();
|
|
var gsAddress = gs.Status.Address;
|
|
var gsPort = gs.Status.Ports[0].Port;
|
|
Debug.Log($"Multiverse is Ready, IP:{gsAddress}, Port:{gsPort}");
|
|
}
|
|
|
|
// Auto shutdown the multiverse in TTL seconds if there is no player connected.
|
|
public async void ShutdownMultiverseInTTL(int ttlInSeconds)
|
|
{
|
|
cancellationTokenSource = new CancellationTokenSource();
|
|
|
|
try
|
|
{
|
|
// Wait for the specified delay.
|
|
await Task.Delay(TimeSpan.FromSeconds(ttlInSeconds), cancellationTokenSource.Token);
|
|
|
|
// Then shutdown the multiverse.
|
|
if (m_Multiverse != null)
|
|
{
|
|
bool ok = await m_Multiverse.Shutdown();
|
|
if (ok) m_Multiverse = null;
|
|
}
|
|
}
|
|
catch (TaskCanceledException)
|
|
{
|
|
Debug.Log("Auto Shutdown task was cancelled.");
|
|
}
|
|
}
|
|
|
|
public void CancelShutdown()
|
|
{
|
|
cancellationTokenSource?.Cancel();
|
|
cancellationTokenSource = null;
|
|
}
|
|
}
|
|
|
|
}
|