BITFALL/Assets/Artists/Scripts/Entity/Inventory/InventoryWeightable.cs

97 lines
2.8 KiB
C#
Raw Normal View History

2023-06-08 14:09:50 +08:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using BITKit;
using BITKit.Entities;
using UnityEngine.AddressableAssets;
namespace BITFALL
{
public interface IWeightedCallback
{
public void OnWeighted(float current, float max);
}
public class InventoryWeightable : EntityComponent,IPlayerEquipCallback
{
[Header(Constant.Header.Data)]
public float currentWeight;
[Header(Constant.Header.Settings)]
public float maxWeight =8;
[Header(Constant.Header.InternalVariables)]
IBasicItemContainer container;
public override void OnStart()
{
base.OnStart();
container = entity.Get<IBasicItemContainer>();
container.AddFactory += AddFactory;
container.OnAdd += OnAdd;
container.OnRemove += OnRemove;
entity.RegisterCallback<IPlayerEquipCallback>(this);
}
bool AddFactory(IBasicItem item)
{
var asset = item.GetAssetable();
if (asset.TryGetProperty<ItemWeight>(out var itemWeight))
{
if (currentWeight + itemWeight <= maxWeight)
{
}
else if(currentWeight+ itemWeight > maxWeight)
{
return false;
}
}
return true;
}
void OnAdd(IBasicItem item)
{
var asset = item.GetAssetable();
if (asset.TryGetProperty<ItemWeight>(out var itemWeight))
{
currentWeight += itemWeight;
InvokeCallback();
}
}
void OnRemove(IBasicItem item)
{
var asset = item.GetAssetable();
if (asset.TryGetProperty<ItemWeight>(out var itemWeight))
{
currentWeight -= itemWeight;
InvokeCallback();
}
}
public void DeEquip(IEquipmentSlot slot, IBasicItem item)
{
if (item.GetAssetable().TryGetProperty<AddInventoryMaxWeight>(out var addWeight))
{
maxWeight -= addWeight.AddWeight;
InvokeCallback();
}
}
public void OnEquip(IEquipmentSlot slot, IBasicItem item)
{
if (item.GetAssetable().TryGetProperty<AddInventoryMaxWeight>(out var addWeight))
{
maxWeight += addWeight.AddWeight;
InvokeCallback();
}
}
void InvokeCallback()
{
foreach (var x in entity.GetCallbacks<IWeightedCallback>())
{
x.OnWeighted(currentWeight, maxWeight);
}
}
}
}