You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
2.6 KiB
C#
82 lines
2.6 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using Unity.Multiplayer.Samples.BossRoom;
|
|
using UnityEngine;
|
|
using Unity.Netcode;
|
|
|
|
public class Scoreboard : NetworkBehaviour
|
|
{
|
|
public List<PlayerItem> playerItems = new();
|
|
public GameObject playerItemPrefab;
|
|
public Transform Parent, FinalParent;
|
|
public GameObject FinalLeaderBoardObj;
|
|
public static Scoreboard instance;
|
|
private bool coroutineStarter = false;
|
|
|
|
private void Awake() => instance = this;
|
|
public void ScoreBoardItemInitializer(ulong clientId, int score, string name)
|
|
{
|
|
if (IsServer) ScoreBoardItemInitializerClientRpc(clientId, score, name);
|
|
}
|
|
[ClientRpc]
|
|
public void ScoreBoardItemInitializerClientRpc(ulong clientId, int score, string name)
|
|
{
|
|
var item = Instantiate(playerItemPrefab, Parent).GetComponent<PlayerItem>();
|
|
item.PlayerName.text = name;
|
|
item.PlayerScore.text = score.ToString();
|
|
item.PlayerClientID = clientId;
|
|
playerItems.Add(item);
|
|
}
|
|
public void ScoreBoardUpdater(string playerName, int score)
|
|
{
|
|
if (IsServer) ScoreBoardUpdaterClientRpc(playerName, score);
|
|
}
|
|
[ClientRpc]
|
|
public void ScoreBoardUpdaterClientRpc(string playerName, int score, ClientRpcParams clientRpcParams = default)
|
|
{
|
|
foreach (var item in playerItems)
|
|
{
|
|
if (item.PlayerName.text == playerName)
|
|
{
|
|
item.PlayerScore.text = score.ToString();
|
|
if (NetworkManager.Singleton.LocalClientId == item.PlayerClientID)
|
|
item.PlayerScore.color = Color.green;
|
|
break;
|
|
}
|
|
}
|
|
SortAndUpdateScoreboard();
|
|
}
|
|
public void FinalLeaderBoard()
|
|
{
|
|
if (IsServer) FinalLeaderBoardClientRPC();
|
|
}
|
|
[ClientRpc]
|
|
public void FinalLeaderBoardClientRPC()
|
|
{
|
|
playerItems.ForEach(item => Instantiate(item.gameObject, FinalParent));
|
|
FinalLeaderBoardObj.SetActive(true);
|
|
}
|
|
private void SortAndUpdateScoreboard()
|
|
{
|
|
playerItems.Sort((p1, p2) => int.Parse(p2.PlayerScore.text).CompareTo(int.Parse(p1.PlayerScore.text)));
|
|
for (int i = 0; i < playerItems.Count; i++) playerItems[i].transform.SetSiblingIndex(i);
|
|
}
|
|
public void StartScoreUpdater()
|
|
{
|
|
if (!coroutineStarter)
|
|
{
|
|
coroutineStarter = true;
|
|
StartCoroutine(ScoreUpdater());
|
|
}
|
|
}
|
|
private IEnumerator ScoreUpdater()
|
|
{
|
|
yield return new WaitUntil(() => coroutineStarter);
|
|
while (true)
|
|
{
|
|
SortAndUpdateScoreboard();
|
|
yield return new WaitForSeconds(0.5f);
|
|
}
|
|
}
|
|
}
|