Files
Northbound/Assets/Scripts/PlayerResourceInventory.cs
dal4segno 4ffbbb0aff 모든 네트워크 오브젝트의 소유권을 서버가 갖도록 함
Distributable -> None
관련 사이드 이펙트로 인한 버그 수정
2026-02-18 02:18:42 +09:00

109 lines
3.2 KiB
C#

using Unity.Netcode;
using UnityEngine;
namespace Northbound
{
public class PlayerResourceInventory : NetworkBehaviour
{
public int maxResourceCapacity = 100;
private int _displayAmount = 0;
public int CurrentResourceAmount => _displayAmount;
public int MaxResourceCapacity => maxResourceCapacity;
private NetworkPlayerController _networkPlayerController;
private bool IsLocalPlayer => _networkPlayerController != null && _networkPlayerController.IsLocalPlayer;
private ulong LocalPlayerId => _networkPlayerController != null ? _networkPlayerController.OwnerPlayerId : OwnerClientId;
private void Awake()
{
_networkPlayerController = GetComponent<NetworkPlayerController>();
}
[Rpc(SendTo.Server)]
private void SetMaxCapacityServerRpc(int maxCapacity, ulong playerId)
{
var resourceManager = ServerResourceManager.Instance;
if (resourceManager != null)
{
resourceManager.SetPlayerMaxCapacity(playerId, maxCapacity);
}
}
public override void OnNetworkSpawn()
{
// _ownerPlayerId 변경 이벤트 구독
if (_networkPlayerController != null)
{
_networkPlayerController.OnOwnerChanged += OnOwnerPlayerIdChanged;
}
TryInitialize();
}
private void OnOwnerPlayerIdChanged(ulong newOwnerId)
{
TryInitialize();
}
private void TryInitialize()
{
if (!IsLocalPlayer) return;
SetMaxCapacityServerRpc(maxResourceCapacity, LocalPlayerId);
RequestResourceUpdateServerRpc(LocalPlayerId);
}
public override void OnNetworkDespawn()
{
if (_networkPlayerController != null)
{
_networkPlayerController.OnOwnerChanged -= OnOwnerPlayerIdChanged;
}
}
[Rpc(SendTo.Server)]
public void RequestResourceUpdateServerRpc(ulong playerId)
{
var resourceManager = ServerResourceManager.Instance;
if (resourceManager != null)
{
int amount = resourceManager.GetPlayerResourceAmount(playerId);
UpdateResourceAmountClientRpc(amount);
}
}
[Rpc(SendTo.ClientsAndHost)]
private void UpdateResourceAmountClientRpc(int amount)
{
_displayAmount = amount;
}
public void UpdateResourceAmountDirectly(int amount)
{
_displayAmount = amount;
}
public bool CanAddResource(int amount)
{
var resourceManager = ServerResourceManager.Instance;
if (resourceManager != null)
{
return resourceManager.CanAddResource(LocalPlayerId, amount);
}
return false;
}
public int GetAvailableSpace()
{
var resourceManager = ServerResourceManager.Instance;
if (resourceManager != null)
{
return resourceManager.GetAvailableSpace(LocalPlayerId);
}
return 0;
}
}
}