Files
my-project/Assets/Inventory/Scripts/WorldItem.cs
2026-04-17 02:14:56 +05:00

101 lines
3.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using UnityEngine;
/// <summary>
/// Предмет в мире — подбирается только по нажатию кнопки E (через charecter.cs).
/// Авто-подбор при касании намеренно убран.
/// </summary>
public class WorldItem : MonoBehaviour
{
public ItemData itemData;
public int amount = 1;
[Header("Pickup")]
public float pickupDelay = 0f;
public float interactRange = 2.5f;
private bool _canPickup;
private bool _setupCalled;
void Start()
{
// Объект размещён в сцене через редактор — Setup() не вызывается,
// поэтому инициализируем pickup здесь.
if (!_setupCalled)
{
if (pickupDelay > 0)
Invoke(nameof(EnablePickup), pickupDelay);
else
_canPickup = true;
}
}
public void Setup(ItemData data, int count)
{
_setupCalled = true;
itemData = data;
amount = count;
// Спавним модель только если визуал ещё не встроен в prefab
if (data.modelPrefab != null && transform.childCount == 0)
{
var model = Instantiate(data.modelPrefab, transform);
model.transform.localPosition = Vector3.zero;
// Удаляем WorldItem из визуальной модели — она только для отображения,
// не должна быть самостоятельным подбираемым объектом
foreach (var wi in model.GetComponentsInChildren<WorldItem>())
Destroy(wi);
}
if (pickupDelay > 0)
Invoke(nameof(EnablePickup), pickupDelay);
else
_canPickup = true;
}
private void EnablePickup() => _canPickup = true;
/// <summary>
/// Вызывается из charecter.cs при нажатии E рядом с предметом.
/// </summary>
public bool TryPickupByButton()
{
if (!_canPickup)
{
Debug.LogWarning("[WorldItem] Cannot pickup — delay not elapsed yet");
return false;
}
if (itemData == null)
{
Debug.LogWarning("[WorldItem] itemData is null!");
return false;
}
if (InventoryManager.Instance == null)
{
Debug.LogWarning("[WorldItem] InventoryManager.Instance is null!");
return false;
}
int remaining = InventoryManager.Instance.AddItem(itemData, amount);
if (remaining <= 0)
{
CancelInvoke(); // отменяем отложенный EnablePickup если он ещё не сработал
Destroy(gameObject);
return true;
}
amount = remaining;
return false;
}
/// <summary>
/// Выбросить предмет с физической силой.
/// </summary>
public void Throw(Vector3 velocity)
{
var rb = GetComponent<Rigidbody>();
if (rb == null) rb = gameObject.AddComponent<Rigidbody>();
rb.linearVelocity = velocity;
}
}