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.
HighGroundRoyaleNetcode/Assets/Scripts/Gameplay/PlatformManager.cs

91 lines
3.2 KiB
C#

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Unity.BossRoom.Gameplay.GameplayObjects.Character;
using Unity.Netcode;
using UnityEngine;
namespace Unity.Multiplayer.Samples.BossRoom
{
public class PlatformManager : NetworkBehaviour
{
public static PlatformManager Instance;
private List<Platform> platforms;
private void Awake()
{
if (Instance != null && Instance != this)
Destroy(gameObject);
else
Instance = this;
}
private void Start()
{
platforms = GetComponentsInChildren<Platform>(true).ToList();
if (IsServer) StartCoroutine(ServerSetup());
else StartCoroutine(ClientSetup());
}
private IEnumerator ServerSetup()
{
yield return new WaitForSeconds(0.5f);
ActivatePlatformsServerRpc();
}
private IEnumerator ClientSetup()
{
yield return new WaitForSeconds(0.5f);
platforms = GetComponentsInChildren<Platform>(true).ToList();
}
[ServerRpc(RequireOwnership = false)]
private void ActivatePlatformsServerRpc()
{
int activeCount = PlayerPrefs.GetInt("NumberOfLobbyPlayers") - 1;
if (activeCount <= 0) return;
platforms.ForEach(p => p.gameObject.SetActive(false));
for (int i = 0; i < activeCount; i++)
platforms[i].gameObject.SetActive(true);
var activeIds = platforms.Where(p => p.gameObject.activeSelf).Select(p => p.PlatformID.Value).ToArray();
ActivatePlatformsClientRpc(activeIds);
}
[ClientRpc]
private void ActivatePlatformsClientRpc(int[] platformIds)
{
platforms = GetComponentsInChildren<Platform>(true).ToList();
platforms.ForEach(p => p.gameObject.SetActive(false));
foreach (int id in platformIds)
platforms.FirstOrDefault(p => p.PlatformID.Value == id)?.gameObject.SetActive(true);
}
public Platform GetNearestAvailablePlatform(Vector3 position)
{
return IsServer ? platforms.Where(p => !p.IsOccupied).OrderBy(p => Vector3.Distance(position, p.transform.position)).FirstOrDefault() : null;
}
public bool AllPlatformsOccupied() => platforms.All(p => p.IsOccupied);
public bool AssignPlayerToPlatform(ServerCharacter player)
{
if (!IsServer) return false;
var availablePlatform = platforms.FirstOrDefault(p => !p.IsOccupied);
if (availablePlatform == null) return false;
availablePlatform.Occupy(player);
return true;
}
public Platform GetPlayerPlatform(ServerCharacter player) => platforms.FirstOrDefault(p => p.IsOccupied && p.GetOccupierId() == player.OwnerClientId);
public Vector3 GetPlatformPosition(int platformId) => platforms.FirstOrDefault(p => p.PlatformID.Value == platformId)?.transform.position ?? Vector3.zero;
public Platform GetPlatformById(int platformId) => platforms.FirstOrDefault(p => p.PlatformID.Value == platformId);
}
}