Files
QuizzinMk5.1/Assets/Quiz/Scripts/PlayerManager.cs
2025-11-12 02:07:33 +00:00

148 lines
3.9 KiB
C#

using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;
public class PlayerManager : UdonSharpBehaviour
{
[UdonSynced] private int[] playerIds = new int[0];
[UdonSynced] private int[] playerScores = new int[0];
[UdonSynced] private string[] playerTeams = new string[0];
[UdonSynced] private int[] currentPlayerIds = new int[0];
public override void OnPlayerJoined(VRCPlayerApi player)
{
if (!Networking.IsOwner(gameObject)) return;
int id = player.playerId;
int index = -1;
for (int i = 0; i < playerIds.Length; i++)
{
if (playerIds[i] == id)
{
index = i;
break;
}
}
if (index == -1)
{
int[] newIds = new int[playerIds.Length + 1];
int[] newScores = new int[playerScores.Length + 1];
string[] newTeams = new string[playerTeams.Length + 1];
for (int i = 0; i < playerIds.Length; i++)
{
newIds[i] = playerIds[i];
newScores[i] = playerScores[i];
newTeams[i] = playerTeams[i];
}
newIds[playerIds.Length] = id;
newScores[playerScores.Length] = 0;
newTeams[playerTeams.Length] = "unassigned";
playerIds = newIds;
playerScores = newScores;
playerTeams = newTeams;
}
// Add to current players
int[] newCurrentIds = new int[currentPlayerIds.Length + 1];
for (int i = 0; i < currentPlayerIds.Length; i++)
{
newCurrentIds[i] = currentPlayerIds[i];
}
newCurrentIds[currentPlayerIds.Length] = id;
currentPlayerIds = newCurrentIds;
RequestSerialization();
}
public override void OnPlayerLeft(VRCPlayerApi player)
{
if (!Networking.IsOwner(gameObject)) return;
// Remove from current players
int[] newCurrentIds = new int[currentPlayerIds.Length - 1];
int j = 0;
for (int i = 0; i < currentPlayerIds.Length; i++)
{
if (currentPlayerIds[i] != player.playerId)
{
newCurrentIds[j] = currentPlayerIds[i];
j++;
}
}
currentPlayerIds = newCurrentIds;
RequestSerialization();
}
public void SetScore(int playerId, int score)
{
if (!Networking.IsOwner(gameObject)) return;
for (int i = 0; i < playerIds.Length; i++)
{
if (playerIds[i] == playerId)
{
playerScores[i] = score;
break;
}
}
RequestSerialization();
}
public int GetScore(int playerId)
{
for (int i = 0; i < playerIds.Length; i++)
{
if (playerIds[i] == playerId)
{
return playerScores[i];
}
}
return 0;
}
public void AssignTeam(int playerId, string team)
{
if (!Networking.IsOwner(gameObject)) return;
if (team == "red" || team == "blue" || team == "unassigned")
{
for (int i = 0; i < playerIds.Length; i++)
{
if (playerIds[i] == playerId)
{
playerTeams[i] = team;
break;
}
}
RequestSerialization();
}
}
public string GetTeam(int playerId)
{
for (int i = 0; i < playerIds.Length; i++)
{
if (playerIds[i] == playerId)
{
return playerTeams[i];
}
}
return "unassigned";
}
public VRCPlayerApi[] GetCurrentPlayers()
{
VRCPlayerApi[] players = new VRCPlayerApi[currentPlayerIds.Length];
for (int i = 0; i < currentPlayerIds.Length; i++)
{
players[i] = VRCPlayerApi.GetPlayerById(currentPlayerIds[i]);
}
return players;
}
}