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

129 lines
4.6 KiB
C#
Raw Permalink 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;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// Пример конфигурации предметов
/// </summary>
public class InventoryExampleItems : MonoBehaviour
{
[Header("Item Database")]
public List<ItemData> items;
void Awake()
{
// Создаём примеры предметов если список пустой
if (items == null || items.Count == 0)
{
items = CreateExampleItems();
}
var im = FindObjectOfType<InventoryManager>();
if (im == null) return;
// Объединяем с существующей базой — не заменяем!
// Так кастомные предметы (tree.asset и т.д.) из Inspector'а сохраняются.
if (im.itemDatabase == null)
im.itemDatabase = new List<ItemData>();
foreach (var item in items)
{
if (item != null && !im.itemDatabase.Exists(x => x?.id == item.id))
im.itemDatabase.Add(item);
}
im.RebuildItemDictionary();
// Тестовые предметы добавляем ТОЛЬКО если нет сохранения
// Иначе они будут перезаписаны загрузкой в Start() и появляться снова при каждом запуске
string savePath = Path.Combine(Application.persistentDataPath, "inventory_save.json");
if (!File.Exists(savePath))
{
im.AddItem("stone", 32);
im.AddItem("dirt", 16);
im.AddItem("wood", 8);
im.AddItem("apple", 5);
im.AddItem("sword", 1);
im.AddItem("pickaxe", 1);
Debug.Log("[InventoryExampleItems] No save found — added test items");
}
else
{
Debug.Log("[InventoryExampleItems] Save exists — skipping test items, load will restore inventory");
}
}
List<ItemData> CreateExampleItems()
{
return new List<ItemData>
{
CreateItem("stone", "Камень", "Обычный камень", ItemType.Block, 64),
CreateItem("dirt", "Земля", "Блок земли", ItemType.Block, 64),
CreateItem("wood", "Дерево", "Деревянный блок", ItemType.Block, 64),
CreateItem("plank", "Доски", "Деревянные доски", ItemType.Block, 64),
CreateItem("sword", "Меч", "Острый меч", ItemType.Weapon, 1),
CreateItem("apple", "Яблоко", "Вкусное яблоко", ItemType.Consumable, 16),
CreateItem("pickaxe", "Кирка", "Инструмент для добычи", ItemType.Tool, 1),
};
}
ItemData CreateItem(string id, string name, string desc, ItemType type, int stack)
{
var item = ScriptableObject.CreateInstance<ItemData>();
item.id = id;
item.itemName = name;
item.description = desc;
item.type = type;
item.maxStack = stack;
item.icon = CreatePlaceholderIcon(name);
return item;
}
Sprite CreatePlaceholderIcon(string text)
{
// Создаём текстуру с текстом
var tex = new Texture2D(64, 64);
var colors = new Color[64 * 64];
// Заливаем цветом (серый фон)
for (int i = 0; i < colors.Length; i++)
{
colors[i] = new Color(0.5f, 0.5f, 0.5f, 1f);
}
tex.SetPixels(colors);
tex.Apply();
// Создаём спрайт
return Sprite.Create(tex, new Rect(0, 0, 64, 64), new Vector2(0.5f, 0.5f));
}
}
/// <summary>
/// Добавляет предметы в инвентарь при старте (для тестирования)
/// </summary>
public class InventoryTester : MonoBehaviour
{
void Start()
{
// Ждём кадр чтобы InventoryManager точно инициализировался
StartCoroutine(AddTestItems());
}
System.Collections.IEnumerator AddTestItems()
{
yield return null; // ждём один кадр
// Добавляем тестовые предметы
var im = InventoryManager.Instance;
if (im != null && im.GetItemCount("stone") == 0) // только если пусто
{
Debug.Log("[InventoryTester] Adding test items...");
im.AddItem("stone", 32);
im.AddItem("dirt", 16);
im.AddItem("wood", 8);
im.AddItem("apple", 5);
im.AddItem("sword", 1);
im.AddItem("pickaxe", 1);
}
}
}