75 lines
2.1 KiB
C#
75 lines
2.1 KiB
C#
|
|
using UnityEngine;
|
||
|
|
using UnityEngine.Networking;
|
||
|
|
using System.Collections;
|
||
|
|
using System.Linq;
|
||
|
|
|
||
|
|
public class RoomManager : MonoBehaviour
|
||
|
|
{
|
||
|
|
[System.Serializable]
|
||
|
|
public class RoomInfo
|
||
|
|
{
|
||
|
|
public string roomId;
|
||
|
|
public int memberCount;
|
||
|
|
public long createdAt;
|
||
|
|
public string[] members;
|
||
|
|
}
|
||
|
|
|
||
|
|
[System.Serializable]
|
||
|
|
public class RoomsResponse
|
||
|
|
{
|
||
|
|
public int count;
|
||
|
|
public RoomInfo[] rooms;
|
||
|
|
}
|
||
|
|
|
||
|
|
private const string API_BASE = "http://localhost:3000/api";
|
||
|
|
|
||
|
|
// 获取所有房间
|
||
|
|
public IEnumerator GetAllRooms(System.Action<RoomInfo[]> callback)
|
||
|
|
{
|
||
|
|
using (UnityWebRequest request = UnityWebRequest.Get($"{API_BASE}/rooms"))
|
||
|
|
{
|
||
|
|
yield return request.SendWebRequest();
|
||
|
|
|
||
|
|
if (request.result == UnityWebRequest.Result.Success)
|
||
|
|
{
|
||
|
|
var json = request.downloadHandler.text;
|
||
|
|
var response = JsonUtility.FromJson<RoomsResponse>(json);
|
||
|
|
callback?.Invoke(response.rooms);
|
||
|
|
}
|
||
|
|
else
|
||
|
|
{
|
||
|
|
Debug.LogError($"获取房间失败: {request.error}");
|
||
|
|
callback?.Invoke(null);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// 获取指定房间的成员
|
||
|
|
public IEnumerator GetRoomMembers(string roomId, System.Action<string[]> callback)
|
||
|
|
{
|
||
|
|
using (UnityWebRequest request = UnityWebRequest.Get($"{API_BASE}/rooms/{roomId}"))
|
||
|
|
{
|
||
|
|
yield return request.SendWebRequest();
|
||
|
|
|
||
|
|
if (request.result == UnityWebRequest.Result.Success)
|
||
|
|
{
|
||
|
|
var json = request.downloadHandler.text;
|
||
|
|
// 解析 members 数组
|
||
|
|
var response = JsonUtility.FromJson<RoomDetailResponse>(json);
|
||
|
|
callback?.Invoke(response.members);
|
||
|
|
}
|
||
|
|
else
|
||
|
|
{
|
||
|
|
callback?.Invoke(null);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
[System.Serializable]
|
||
|
|
private class RoomDetailResponse
|
||
|
|
{
|
||
|
|
public string roomId;
|
||
|
|
public string[] members;
|
||
|
|
public int memberCount;
|
||
|
|
}
|
||
|
|
}
|