fix чать инвенторя
This commit is contained in:
@@ -1,302 +1,133 @@
|
||||
using UnityEngine;
|
||||
using UnityEditor;
|
||||
using UnityEngine.UI;
|
||||
using UnityEngine.EventSystems;
|
||||
using TMPro;
|
||||
|
||||
public class InventorySceneSetup
|
||||
/// <summary>
|
||||
/// Tools > Setup Complete Scene — создаёт всё до запуска игры (editor-time).
|
||||
/// Canvas инвентаря помещается внутрь Player.
|
||||
/// InventoryManager получает все ссылки сразу.
|
||||
/// </summary>
|
||||
public static class InventorySceneSetup
|
||||
{
|
||||
[MenuItem("Tools/Create Player")]
|
||||
public static void CreatePlayer()
|
||||
[MenuItem("Tools/Setup Complete Scene")]
|
||||
public static void SetupCompleteScene()
|
||||
{
|
||||
if (Object.FindObjectOfType<InventoryManager>() != null)
|
||||
{
|
||||
EditorUtility.DisplayDialog(
|
||||
"Сцена уже настроена",
|
||||
"InventoryManager уже существует. Удалите существующие объекты сцены перед повторной настройкой.",
|
||||
"OK");
|
||||
return;
|
||||
}
|
||||
|
||||
// ── EventSystem ───────────────────────────────────────────────────────
|
||||
if (Object.FindObjectOfType<EventSystem>() == null)
|
||||
{
|
||||
var esGO = new GameObject("EventSystem");
|
||||
esGO.AddComponent<EventSystem>();
|
||||
esGO.AddComponent<StandaloneInputModule>();
|
||||
}
|
||||
|
||||
// ── InventoryEvents ───────────────────────────────────────────────────
|
||||
new GameObject("InventoryEvents").AddComponent<InventoryEvents>();
|
||||
|
||||
// ── InventoryManager ──────────────────────────────────────────────────
|
||||
var imGO = new GameObject("InventoryManager");
|
||||
var im = imGO.AddComponent<InventoryManager>();
|
||||
imGO.AddComponent<InventoryExampleItems>();
|
||||
|
||||
// ── Player ────────────────────────────────────────────────────────────
|
||||
var player = CreatePlayerGO();
|
||||
|
||||
// ── InventoryCanvas (дочерний объект Player) ──────────────────────────
|
||||
var canvasGO = new GameObject("InventoryCanvas");
|
||||
canvasGO.transform.SetParent(player.transform, false);
|
||||
|
||||
var canvas = canvasGO.AddComponent<Canvas>();
|
||||
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
|
||||
canvas.sortingOrder = 100;
|
||||
canvasGO.AddComponent<GraphicRaycaster>();
|
||||
|
||||
var uiBuilder = canvasGO.AddComponent<InventoryUIBuilder>();
|
||||
|
||||
// Строим весь UI прямо сейчас, до запуска игры
|
||||
uiBuilder.BuildInventoryUI();
|
||||
|
||||
// Назначаем ссылки в InventoryManager
|
||||
im.slots = uiBuilder.GetInventorySlots();
|
||||
im.hotbarSlots = uiBuilder.GetHotbarSlots();
|
||||
im.inventoryPanel = uiBuilder.inventoryPanelRect != null ? uiBuilder.inventoryPanelRect.gameObject : null;
|
||||
im.inventoryCanvas = canvas;
|
||||
|
||||
// Скрыть панель инвентаря по умолчанию
|
||||
if (im.inventoryPanel != null)
|
||||
im.inventoryPanel.SetActive(false);
|
||||
|
||||
// ── PlayerInput (дочерний объект Player) ──────────────────────────────
|
||||
var piGO = new GameObject("PlayerInput");
|
||||
piGO.transform.SetParent(player.transform, false);
|
||||
var pi = piGO.AddComponent<PlayerInput>();
|
||||
var inputActions = AssetDatabase.LoadAssetAtPath<UnityEngine.InputSystem.InputActionAsset>(
|
||||
"Assets/Input/PlayerControls.inputactions");
|
||||
if (inputActions != null)
|
||||
pi.actions = inputActions;
|
||||
else
|
||||
Debug.LogWarning("[Setup] Назначьте Assets/Input/PlayerControls.inputactions на компонент PlayerInput вручную.");
|
||||
|
||||
// ── HandEquipSystem ───────────────────────────────────────────────────
|
||||
player.AddComponent<HandEquipSystem>();
|
||||
|
||||
Selection.activeGameObject = player;
|
||||
Debug.Log("[Setup] Готово! Назначьте кость руки (handBone) в HandEquipSystem на Player.");
|
||||
}
|
||||
|
||||
// ── Вспомогательные методы ────────────────────────────────────────────────
|
||||
|
||||
static GameObject CreatePlayerGO()
|
||||
{
|
||||
var go = new GameObject("Player");
|
||||
|
||||
var cc = go.AddComponent<CharacterController>();
|
||||
var cc = go.AddComponent<CharacterController>();
|
||||
cc.height = 1.8f;
|
||||
cc.radius = 0.5f;
|
||||
cc.center = new Vector3(0, 0.9f, 0);
|
||||
|
||||
var character = go.AddComponent<charecter>();
|
||||
character.walkSpeed = 5f;
|
||||
character.runSpeed = 9f;
|
||||
character.crouchSpeed = 2.5f;
|
||||
character.jumpHeight = 1.5f;
|
||||
character.gravity = -9.81f;
|
||||
var ch = go.AddComponent<charecter>();
|
||||
ch.walkSpeed = 5f;
|
||||
ch.runSpeed = 9f;
|
||||
ch.crouchSpeed = 2.5f;
|
||||
ch.jumpHeight = 1.5f;
|
||||
ch.gravity = -9.81f;
|
||||
|
||||
GameObject body = GameObject.CreatePrimitive(PrimitiveType.Capsule);
|
||||
// Визуальная капсула
|
||||
var body = GameObject.CreatePrimitive(PrimitiveType.Capsule);
|
||||
body.name = "Body";
|
||||
body.transform.SetParent(go.transform);
|
||||
body.transform.localPosition = Vector3.zero;
|
||||
GameObject.Destroy(body.GetComponent<Collider>());
|
||||
body.transform.SetParent(go.transform, false);
|
||||
Object.DestroyImmediate(body.GetComponent<Collider>());
|
||||
|
||||
GameObject head = new GameObject("Head");
|
||||
head.transform.SetParent(go.transform);
|
||||
// Голова
|
||||
var head = new GameObject("Head");
|
||||
head.transform.SetParent(go.transform, false);
|
||||
head.transform.localPosition = new Vector3(0, 0.8f, 0);
|
||||
character.head = head.transform;
|
||||
ch.head = head.transform;
|
||||
|
||||
GameObject camObj = new GameObject("PlayerCamera");
|
||||
camObj.transform.SetParent(head.transform);
|
||||
// Камера
|
||||
var camObj = new GameObject("PlayerCamera");
|
||||
camObj.transform.SetParent(head.transform, false);
|
||||
camObj.transform.localPosition = new Vector3(0, 0.1f, 0);
|
||||
var cam = camObj.AddComponent<Camera>();
|
||||
cam.tag = "MainCamera";
|
||||
var cam = camObj.AddComponent<Camera>();
|
||||
cam.tag = "MainCamera";
|
||||
cam.nearClipPlane = 0.05f;
|
||||
|
||||
var existingCam = GameObject.FindGameObjectWithTag("MainCamera");
|
||||
if (existingCam != null && existingCam != camObj)
|
||||
{
|
||||
GameObject.Destroy(existingCam);
|
||||
}
|
||||
var oldCam = GameObject.FindWithTag("MainCamera");
|
||||
if (oldCam != null && oldCam != camObj)
|
||||
Object.DestroyImmediate(oldCam);
|
||||
|
||||
go.tag = "Player";
|
||||
go.transform.position = new Vector3(0, 2, -5);
|
||||
|
||||
Selection.activeGameObject = go;
|
||||
Debug.Log("[Tools] Создан игрок!");
|
||||
return go;
|
||||
}
|
||||
|
||||
[MenuItem("Tools/Create Item Prefab")]
|
||||
public static void CreateItemPrefab()
|
||||
{
|
||||
var itemGO = new GameObject("NewItem");
|
||||
itemGO.AddComponent<WorldItem>();
|
||||
|
||||
var sphere = itemGO.AddComponent<SphereCollider>();
|
||||
sphere.radius = 0.5f;
|
||||
sphere.isTrigger = true;
|
||||
|
||||
var visual = GameObject.CreatePrimitive(PrimitiveType.Cube);
|
||||
visual.name = "Visual";
|
||||
visual.transform.SetParent(itemGO.transform);
|
||||
visual.transform.localPosition = Vector3.zero;
|
||||
visual.transform.localScale = new Vector3(0.3f, 0.3f, 0.3f);
|
||||
GameObject.Destroy(visual.GetComponent<Collider>());
|
||||
|
||||
Selection.activeGameObject = itemGO;
|
||||
Debug.Log("[Tools] Создан префаб предмета!");
|
||||
}
|
||||
|
||||
[MenuItem("Tools/Create Test Item in Scene")]
|
||||
public static void CreateTestItem()
|
||||
{
|
||||
// Создаём тестовый предмет в сцене
|
||||
var itemGO = new GameObject("TestItem");
|
||||
itemGO.transform.position = new Vector3(0, 0.5f, 3);
|
||||
|
||||
// Визуал
|
||||
var visual = GameObject.CreatePrimitive(PrimitiveType.Cube);
|
||||
visual.name = "Visual";
|
||||
visual.transform.SetParent(itemGO.transform);
|
||||
visual.transform.localPosition = Vector3.zero;
|
||||
visual.transform.localScale = Vector3.one * 0.3f;
|
||||
GameObject.Destroy(visual.GetComponent<Collider>());
|
||||
|
||||
// Компонент предмета
|
||||
var worldItem = itemGO.AddComponent<WorldItem>();
|
||||
worldItem.useFactory = false;
|
||||
|
||||
// Тестовые данные
|
||||
var testItem = ScriptableObject.CreateInstance<ItemData>();
|
||||
testItem.id = "test_item";
|
||||
testItem.itemName = "Тестовый предмет";
|
||||
testItem.description = "Просто тестовый предмет";
|
||||
testItem.type = ItemType.Material;
|
||||
testItem.maxStack = 64;
|
||||
|
||||
// Используем Setup чтобы инициализировать визуал и включить мгновенный подбор
|
||||
worldItem.Setup(testItem, 5);
|
||||
|
||||
// Коллайдер для подбора (trigger для обычных коллайдеров)
|
||||
var box = itemGO.AddComponent<BoxCollider>();
|
||||
box.isTrigger = true;
|
||||
box.size = Vector3.one;
|
||||
|
||||
Selection.activeGameObject = itemGO;
|
||||
Debug.Log("[Tools] Создан тестовый предмет! Подойдите к нему игроком.");
|
||||
}
|
||||
|
||||
[MenuItem("Tools/Setup Inventory Scene")]
|
||||
public static void SetupScene()
|
||||
{
|
||||
var scene = UnityEngine.SceneManagement.SceneManager.GetActiveScene();
|
||||
var rootObjects = scene.GetRootGameObjects();
|
||||
|
||||
foreach (var root in rootObjects)
|
||||
{
|
||||
if (root.GetComponent<InventoryManager>() != null)
|
||||
{
|
||||
Debug.LogWarning("InventoryManager уже существует!");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Создаём GameManager
|
||||
var gameManager = new GameObject("GameManager");
|
||||
var im = gameManager.AddComponent<InventoryManager>();
|
||||
gameManager.AddComponent<InventoryExampleItems>();
|
||||
gameManager.AddComponent<InventoryTester>();
|
||||
|
||||
// Создаём Canvas
|
||||
var canvasGO = new GameObject("InventoryCanvas");
|
||||
var canvas = canvasGO.AddComponent<Canvas>();
|
||||
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
|
||||
canvas.sortingOrder = 100;
|
||||
canvasGO.AddComponent<GraphicRaycaster>();
|
||||
|
||||
// Ensure EventSystem exists for UI interaction
|
||||
var existingES = GameObject.FindObjectOfType<UnityEngine.EventSystems.EventSystem>();
|
||||
if (existingES == null)
|
||||
{
|
||||
var es = new GameObject("EventSystem");
|
||||
es.AddComponent<UnityEngine.EventSystems.EventSystem>();
|
||||
es.AddComponent<UnityEngine.EventSystems.StandaloneInputModule>();
|
||||
}
|
||||
|
||||
// Создаём панель инвентаря
|
||||
var inventoryPanel = CreatePanel(canvasGO.transform, "InventoryPanel", new Color(0.15f, 0.15f, 0.15f, 0.95f));
|
||||
var inventoryRect = inventoryPanel.GetComponent<RectTransform>();
|
||||
SetRect(inventoryRect, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), Vector2.zero, new Vector2(500, 300));
|
||||
|
||||
// Заголовок
|
||||
CreateTitle(inventoryPanel.transform, "Инвентарь", new Vector2(0, 130));
|
||||
|
||||
// Сетка инвентаря (4x9 = 36 слотов)
|
||||
var inventoryGrid = CreateGrid(inventoryPanel.transform, "InventoryGrid", 9, 4, 50, 4, new Vector2(10, 40));
|
||||
im.slots = CreateSlots(inventoryGrid, "InventorySlot_", 0, 36);
|
||||
|
||||
// Создаём хотбар
|
||||
var hotbarPanel = CreatePanel(canvasGO.transform, "HotbarPanel", new Color(0.1f, 0.1f, 0.1f, 0.9f));
|
||||
var hotbarRect = hotbarPanel.GetComponent<RectTransform>();
|
||||
SetRect(hotbarRect, new Vector2(0.5f, 0f), new Vector2(0.5f, 0f), new Vector2(0, 15), new Vector2(460, 60));
|
||||
|
||||
var hotbarGrid = CreateGrid(hotbarPanel.transform, "HotbarGrid", 9, 1, 50, 4, new Vector2(10, 10));
|
||||
im.hotbarSlots = CreateSlots(hotbarGrid, "HotbarSlot_", 0, 9);
|
||||
|
||||
// Подключаем ссылку на панель
|
||||
im.inventoryPanel = inventoryPanel;
|
||||
im.inventoryCanvas = canvas;
|
||||
|
||||
// Скрываем панель
|
||||
inventoryPanel.SetActive(false);
|
||||
|
||||
Debug.Log("[Tools] Инвентарь настроен! (36 слотов + 9 хотбар)");
|
||||
}
|
||||
|
||||
static GameObject CreatePanel(Transform parent, string name, Color color)
|
||||
{
|
||||
var panel = new GameObject(name);
|
||||
panel.transform.SetParent(parent, false);
|
||||
panel.AddComponent<RectTransform>();
|
||||
panel.AddComponent<Image>().color = color;
|
||||
return panel;
|
||||
}
|
||||
|
||||
static void SetRect(RectTransform rect, Vector2 anchorMin, Vector2 anchorMax, Vector2 anchoredPosition, Vector2 sizeDelta)
|
||||
{
|
||||
rect.anchorMin = anchorMin;
|
||||
rect.anchorMax = anchorMax;
|
||||
rect.pivot = new Vector2(0.5f, 0.5f);
|
||||
rect.anchoredPosition = anchoredPosition;
|
||||
rect.sizeDelta = sizeDelta;
|
||||
}
|
||||
|
||||
static void CreateTitle(Transform parent, string text, Vector2 position)
|
||||
{
|
||||
var titleObj = new GameObject("Title");
|
||||
titleObj.transform.SetParent(parent, false);
|
||||
var rect = titleObj.AddComponent<RectTransform>();
|
||||
rect.anchorMin = new Vector2(0, 1);
|
||||
rect.anchorMax = new Vector2(1, 1);
|
||||
rect.pivot = new Vector2(0.5f, 1);
|
||||
rect.anchoredPosition = position;
|
||||
rect.sizeDelta = new Vector2(-20, 30);
|
||||
|
||||
var tmp = titleObj.AddComponent<TextMeshProUGUI>();
|
||||
tmp.text = text;
|
||||
tmp.fontSize = 18;
|
||||
tmp.alignment = TextAlignmentOptions.Center;
|
||||
tmp.color = Color.white;
|
||||
}
|
||||
|
||||
static Transform CreateGrid(Transform parent, string name, int cols, int rows, float cellSize, float spacing, Vector2 offset)
|
||||
{
|
||||
var gridObj = new GameObject(name);
|
||||
gridObj.transform.SetParent(parent, false);
|
||||
var rect = gridObj.AddComponent<RectTransform>();
|
||||
rect.anchorMin = Vector2.zero;
|
||||
rect.anchorMax = Vector2.one;
|
||||
rect.offsetMin = offset;
|
||||
rect.offsetMax = -offset;
|
||||
|
||||
var grid = gridObj.AddComponent<GridLayoutGroup>();
|
||||
grid.cellSize = new Vector2(cellSize, cellSize);
|
||||
grid.spacing = new Vector2(spacing, spacing);
|
||||
grid.startCorner = GridLayoutGroup.Corner.UpperLeft;
|
||||
grid.startAxis = GridLayoutGroup.Axis.Horizontal;
|
||||
grid.constraint = GridLayoutGroup.Constraint.FixedColumnCount;
|
||||
grid.constraintCount = cols;
|
||||
|
||||
return gridObj.transform;
|
||||
}
|
||||
|
||||
static Slot[] CreateSlots(Transform parent, string prefix, int startIndex, int count)
|
||||
{
|
||||
var slots = new Slot[count];
|
||||
var slotSize = 50f;
|
||||
var emptyColor = new Color(0.25f, 0.25f, 0.25f, 0.8f);
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
var slotObj = new GameObject(prefix + (startIndex + i));
|
||||
slotObj.transform.SetParent(parent, false);
|
||||
slotObj.AddComponent<RectTransform>().sizeDelta = new Vector2(slotSize, slotSize);
|
||||
|
||||
var bg = slotObj.AddComponent<Image>();
|
||||
bg.color = emptyColor;
|
||||
|
||||
var slot = slotObj.AddComponent<Slot>();
|
||||
slot.slotIndex = startIndex + i;
|
||||
|
||||
// Icon
|
||||
var iconObj = new GameObject("Icon");
|
||||
iconObj.transform.SetParent(slotObj.transform, false);
|
||||
var iconRect = iconObj.AddComponent<RectTransform>();
|
||||
iconRect.anchorMin = Vector2.zero;
|
||||
iconRect.anchorMax = Vector2.one;
|
||||
iconRect.offsetMin = new Vector2(4, 4);
|
||||
iconRect.offsetMax = new Vector2(-4, -4);
|
||||
slot.iconImage = iconObj.AddComponent<Image>();
|
||||
slot.iconImage.preserveAspect = true;
|
||||
slot.iconImage.enabled = false;
|
||||
|
||||
// Amount panel
|
||||
var amountObj = new GameObject("AmountPanel");
|
||||
amountObj.transform.SetParent(slotObj.transform, false);
|
||||
var amountRect = amountObj.AddComponent<RectTransform>();
|
||||
amountRect.anchorMin = Vector2.one;
|
||||
amountRect.anchorMax = Vector2.one;
|
||||
amountRect.pivot = new Vector2(1, 0);
|
||||
amountRect.anchoredPosition = new Vector2(-2, 2);
|
||||
amountRect.sizeDelta = new Vector2(22, 22);
|
||||
slot.amountPanel = amountObj;
|
||||
slot.amountPanel.SetActive(false);
|
||||
|
||||
amountObj.AddComponent<Image>().color = new Color(0, 0, 0, 0.7f);
|
||||
|
||||
var amountTextObj = new GameObject("Text");
|
||||
amountTextObj.transform.SetParent(amountObj.transform, false);
|
||||
amountTextObj.AddComponent<RectTransform>().sizeDelta = new Vector2(20, 20);
|
||||
slot.amountText = amountTextObj.AddComponent<TextMeshProUGUI>();
|
||||
slot.amountText.fontSize = 14;
|
||||
slot.amountText.alignment = TextAlignmentOptions.Right;
|
||||
slot.amountText.color = Color.white;
|
||||
slot.amountText.fontStyle = FontStyles.Bold;
|
||||
|
||||
// Drag & Drop
|
||||
var dragDrop = slotObj.AddComponent<InventoryDragDrop>();
|
||||
dragDrop.slot = slot;
|
||||
dragDrop.slotIndex = slot.slotIndex;
|
||||
|
||||
slots[i] = slot;
|
||||
}
|
||||
|
||||
return slots;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user