BITFALL/Assets/Artists/Scripts/Entities/Inventory/PlayerInventorySwap.cs

104 lines
2.6 KiB
C#
Raw Normal View History

2023-10-24 23:37:59 +08:00
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using BITFALL.Entities.Inventory;
using BITFALL.Items;
using BITKit;
using BITKit.Entities;
using BITKit.Selection;
using UnityEngine;
namespace BITFALL.Player.Inventory
{
[CustomType(typeof(IEntitySwapItem))]
2023-10-30 01:25:53 +08:00
public class PlayerInventorySwap : EntityBehavior,IEntitySwapItem
2023-10-24 23:37:59 +08:00
{
public bool TryGetCurrentContainer(out IBasicItemContainer container)
{
container = _currentContainer;
return container is not null;
}
public event Func<IBasicItemContainer, bool> OpenSwapFactory;
public event Action<IBasicItemContainer> OnSwapOpened;
public event Action<IBasicItemContainer> OnSwapClosed;
[Inject] private ISelector _selector;
[Inject] private IHealth _health;
[Inject] private IEntityInventory _inventory;
private IBasicItemContainer _currentContainer;
public override void OnStart()
{
base.OnStart();
_selector.OnActive += OnActive;
_health.OnSetAlive += OnSetAlive;
2024-04-10 18:12:40 +08:00
Data.AddListener<PlayerTradeWithTrader>(OnTrade);
Data.AddListener<PlayerSwapWithContainer>(OnSwapCommand);
}
private void OnSwapCommand(PlayerSwapWithContainer obj)
{
Open(obj.Container);
}
private void OnTrade(PlayerTradeWithTrader obj)
{
}
public override void OnDestroyComponent()
{
Data.RemoveListender<PlayerSwapWithContainer>(OnSwapCommand);
Data.RemoveListender<PlayerTradeWithTrader>(OnTrade);
2023-10-24 23:37:59 +08:00
}
private void OnSetAlive(bool obj)
{
if (obj is false)
{
Close();
}
}
private void OnActive(ISelectable obj)
{
if (_currentContainer is not null) return;
if (obj.Transform.TryGetComponent<IBasicItemContainer>(out var container) is false) return;
Open(container);
}
public bool Add(IBasicItem item)
{
if (_currentContainer is null) return false;
return _inventory.Add(item) && _currentContainer.Remove(item);
}
public bool Remove(IBasicItem item)
{
if (_currentContainer is null) return false;
return _currentContainer.Add(item) && _inventory.Remove(item);
}
public bool Open(IBasicItemContainer container)
{
if (_currentContainer is not null) return false;
if (OpenSwapFactory.CastAsFunc().Any(x=>x.Invoke(container) is false)) return false;
_currentContainer = container;
OnSwapOpened?.Invoke(_currentContainer);
2024-04-10 18:12:40 +08:00
container.AddHandle(GetInstanceID());
2023-10-24 23:37:59 +08:00
return true;
}
public bool Close()
{
if (_currentContainer is null) return false;
OnSwapClosed?.Invoke(_currentContainer);
2024-04-10 18:12:40 +08:00
_currentContainer.RemoveHandle(GetInstanceID());
2023-10-24 23:37:59 +08:00
_currentContainer = null;
return true;
}
}
}