Files
Net.Like.Xue.Tokyo/Packages-Local/Com.Project.B.Unity/BuyStation/UnityBuyStationService.cs

80 lines
2.9 KiB
C#
Raw Normal View History

2025-06-24 23:49:13 +08:00
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using BITKit;
using BITKit.Entities;
using BITKit.Mod;
using Cysharp.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Net.Project.B.Interaction;
using Net.Project.B.Item;
using Project.B.Item;
using UnityEngine;
namespace Net.Project.B.Inventory
{
public class UnityBuyStationService : IBuyStationService
{
private readonly IWorldInteractionService _interactionService;
private readonly ILogger<UnityBuyStationService> _logger;
private readonly IManagedItemService _itemService;
private readonly IEntitiesService _entitiesService;
public UnityBuyStationService(IEntitiesService entitiesService, IManagedItemService itemService, IWorldInteractionService interactionService, ILogger<UnityBuyStationService> logger)
{
_entitiesService = entitiesService;
_itemService = itemService;
_interactionService = interactionService;
_logger = logger;
}
public UniTask<IReadOnlyList<BuyStationComponent>> GetAllItemList()
{
var result = _entitiesService.QueryComponents<ScriptableBuyStationItemList>().ToArray().SelectMany(scriptableBuyStationItemList => scriptableBuyStationItemList.ItemList).ToArray();;
return UniTask.FromResult<IReadOnlyList<BuyStationComponent>>(result);
}
public async UniTask<bool> BuyItem(int buyer, BuyStationComponent buyStationComponent)
{
if (_entitiesService
.QueryComponents<ScriptableItem>().ToArray().FirstOrDefault(x => x.Id == buyStationComponent.ScriptableId) is not { } item)
{
_logger.LogWarning($"未找到ID为:{buyStationComponent.ScriptableId}的物品");
return false;
}
if (_entitiesService.TryGetEntity(buyer, out var entity) &&
entity.ServiceProvider.QueryComponents(out Transform transform))
{
var runtimeItem = item.CreateRuntimeItem();
var go = await _itemService.InstanceItem(transform.position, transform.rotation, runtimeItem);
if (go is GameObject gameObject &&
_entitiesService.TryGetEntity(gameObject.GetInstanceID(), out var itemEntity) &&
itemEntity.ServiceProvider.QueryComponents(out IWorldInteractable interactable))
{
_interactionService.Interaction(entity, interactable);
}
else
{
_logger.LogInformation("已购买物品,但未自动互动");
}
return true;
}
_logger.LogWarning($"未找到ID为:{buyer}的角色或玩家");
return false;
}
}
}