102 lines
2.9 KiB
C#
102 lines
2.9 KiB
C#
using Unity.Netcode;
|
|
using UnityEngine;
|
|
using System.Collections.Generic;
|
|
|
|
namespace Northbound
|
|
{
|
|
public class ServerResourceManager : NetworkBehaviour
|
|
{
|
|
public static ServerResourceManager Instance { get; private set; }
|
|
|
|
private Dictionary<ulong, int> _playerResources = new Dictionary<ulong, int>();
|
|
private NetworkVariable<int> _resourcesData = new NetworkVariable<int>();
|
|
|
|
private void Awake()
|
|
{
|
|
if (Instance != null && Instance != this)
|
|
{
|
|
Destroy(gameObject);
|
|
return;
|
|
}
|
|
Instance = this;
|
|
}
|
|
|
|
public override void OnNetworkSpawn()
|
|
{
|
|
if (IsServer)
|
|
{
|
|
Instance = this;
|
|
NetworkManager.Singleton.OnClientConnectedCallback += OnClientConnected;
|
|
NetworkManager.Singleton.OnClientDisconnectCallback += OnClientDisconnected;
|
|
}
|
|
}
|
|
|
|
public override void OnNetworkDespawn()
|
|
{
|
|
if (IsServer)
|
|
{
|
|
if (NetworkManager.Singleton != null)
|
|
{
|
|
NetworkManager.Singleton.OnClientConnectedCallback -= OnClientConnected;
|
|
NetworkManager.Singleton.OnClientDisconnectCallback -= OnClientDisconnected;
|
|
}
|
|
}
|
|
}
|
|
|
|
private void OnClientConnected(ulong clientId)
|
|
{
|
|
_playerResources[clientId] = 0;
|
|
}
|
|
|
|
private void OnClientDisconnected(ulong clientId)
|
|
{
|
|
_playerResources.Remove(clientId);
|
|
}
|
|
|
|
public int GetPlayerResourceAmount(ulong clientId)
|
|
{
|
|
if (_playerResources.TryGetValue(clientId, out var resource))
|
|
{
|
|
return resource;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
public bool CanAddResource(ulong clientId, int amount)
|
|
{
|
|
if (_playerResources.TryGetValue(clientId, out var resource))
|
|
{
|
|
return resource + amount <= 100;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public int GetAvailableSpace(ulong clientId)
|
|
{
|
|
if (_playerResources.TryGetValue(clientId, out var resource))
|
|
{
|
|
return 100 - resource;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
public void AddResource(ulong clientId, int amount)
|
|
{
|
|
if (_playerResources.TryGetValue(clientId, out var resource))
|
|
{
|
|
int actualAmount = Mathf.Min(amount, 100 - resource);
|
|
_playerResources[clientId] = resource + actualAmount;
|
|
}
|
|
}
|
|
|
|
public void RemoveResource(ulong clientId, int amount)
|
|
{
|
|
if (_playerResources.TryGetValue(clientId, out var resource))
|
|
{
|
|
int actualAmount = Mathf.Min(amount, resource);
|
|
_playerResources[clientId] = resource - actualAmount;
|
|
}
|
|
}
|
|
}
|
|
}
|