From 057f5d3d1e0dfd770e50d08d61053eadaccad487 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 15 Apr 2026 20:04:28 +0500 Subject: [PATCH] test --- .../Inventory/Scripts/InventoryItemFactory.cs | 13 +++ Assets/Inventory/Scripts/InventoryManager.cs | 98 +++++++++++++------ .../Inventory/Scripts/InventorySceneSetup.cs | 14 ++- .../scripts/PlayerInput.cs | 79 +++++++++++++++ .../scripts/PlayerInput.cs.meta | 2 + .../charecter-controller/scripts/charecter.cs | 37 ++++--- 6 files changed, 198 insertions(+), 45 deletions(-) create mode 100644 Assets/charecter-controller/scripts/PlayerInput.cs create mode 100644 Assets/charecter-controller/scripts/PlayerInput.cs.meta diff --git a/Assets/Inventory/Scripts/InventoryItemFactory.cs b/Assets/Inventory/Scripts/InventoryItemFactory.cs index ffe5d1c..860a208 100644 --- a/Assets/Inventory/Scripts/InventoryItemFactory.cs +++ b/Assets/Inventory/Scripts/InventoryItemFactory.cs @@ -181,6 +181,19 @@ public class InventoryItemFactory : MonoBehaviour rb.linearVelocity = velocity.Value + (Vector3.up * (config?.dropForce ?? 2f)); } + // Если у ItemData нет связанной модели — создаём простой визуал (куб) + if (itemData != null && itemData.modelPrefab == null && worldItem != null) + { + var visual = GameObject.CreatePrimitive(PrimitiveType.Cube); + visual.name = "Visual"; + visual.transform.SetParent(worldItem.transform, false); + visual.transform.localPosition = Vector3.zero; + visual.transform.localScale = Vector3.one * 0.3f; + // Удаляем лишний коллайдер на визуале + var col = visual.GetComponent(); + if (col != null) GameObject.Destroy(col); + } + return worldItem; } diff --git a/Assets/Inventory/Scripts/InventoryManager.cs b/Assets/Inventory/Scripts/InventoryManager.cs index ccd62f6..743f7c1 100644 --- a/Assets/Inventory/Scripts/InventoryManager.cs +++ b/Assets/Inventory/Scripts/InventoryManager.cs @@ -1,6 +1,7 @@ using UnityEngine; using System.Collections.Generic; using UnityEngine.Events; +using System.IO; public class InventoryManager : MonoBehaviour { @@ -108,37 +109,22 @@ public class InventoryManager : MonoBehaviour var eventsGO = new GameObject("InventoryEvents"); eventsGO.AddComponent(); } + + // Попробуем загрузить сохранённый инвентарь + LoadFromFile(); + + // Ensure PlayerInput exists and subscribe to input events + if (PlayerInput.Instance == null) + { + var go = new GameObject("PlayerInput"); + go.AddComponent(); + } + + PlayerInput.Instance.OnToggleInventory += ToggleInventory; + PlayerInput.Instance.OnDropPressed += DropSelectedItem; + PlayerInput.Instance.OnHotbarSelect += SelectHotbarSlot; } - - void Update() - { - // Toggle инвентаря на Tab - if (Input.GetKeyDown(KeyCode.Tab)) - { - ToggleInventory(); - } - - // Закрыть на Escape - if (Input.GetKeyDown(KeyCode.Escape) && inventoryPanel != null && inventoryPanel.activeSelf) - { - ToggleInventory(); - } - - // Горячие клавиши 1-9 для хотбара - for (int i = 0; i < 9; i++) - { - if (Input.GetKeyDown(KeyCode.Alpha1 + i)) - { - SelectHotbarSlot(i); - } - } - - // Выброс предмета на Q - if (Input.GetKeyDown(KeyCode.Q)) - { - DropSelectedItem(); - } - } + public void ToggleInventory() { @@ -151,11 +137,15 @@ public class InventoryManager : MonoBehaviour { Cursor.lockState = CursorLockMode.None; InventoryEvents.Instance?.OnInventoryOpened?.Invoke(); + if (PlayerInput.Instance != null) + PlayerInput.Instance.Enabled = false; } else { Cursor.lockState = CursorLockMode.Locked; InventoryEvents.Instance?.OnInventoryClosed?.Invoke(); + if (PlayerInput.Instance != null) + PlayerInput.Instance.Enabled = true; } } } @@ -568,6 +558,49 @@ public class InventoryManager : MonoBehaviour return JsonUtility.ToJson(inventoryData, true); } + /// + /// Сохранить инвентарь в файл (Application.persistentDataPath) + /// + public void SaveToFile() + { + try + { + string json = ExportToJson(); + string path = Path.Combine(Application.persistentDataPath, "inventory_save.json"); + File.WriteAllText(path, json); + Debug.Log($"[InventoryManager] Saved inventory to: {path}"); + } + catch (System.Exception ex) + { + Debug.LogError($"[InventoryManager] Failed to save inventory: {ex}"); + } + } + + /// + /// Загрузить инвентарь из файла (если есть) + /// + public void LoadFromFile() + { + try + { + string path = Path.Combine(Application.persistentDataPath, "inventory_save.json"); + if (File.Exists(path)) + { + string json = File.ReadAllText(path); + ImportFromJson(json); + Debug.Log($"[InventoryManager] Loaded inventory from: {path}"); + } + else + { + Debug.Log("[InventoryManager] No save file found."); + } + } + catch (System.Exception ex) + { + Debug.LogError($"[InventoryManager] Failed to load inventory: {ex}"); + } + } + public void ImportFromJson(string json) { var inventoryData = JsonUtility.FromJson(json); @@ -598,4 +631,9 @@ public class InventoryManager : MonoBehaviour public string itemId; public int amount; } + + void OnApplicationQuit() + { + SaveToFile(); + } } \ No newline at end of file diff --git a/Assets/Inventory/Scripts/InventorySceneSetup.cs b/Assets/Inventory/Scripts/InventorySceneSetup.cs index 1692b89..1117bf4 100644 --- a/Assets/Inventory/Scripts/InventorySceneSetup.cs +++ b/Assets/Inventory/Scripts/InventorySceneSetup.cs @@ -90,7 +90,6 @@ public class InventorySceneSetup // Компонент предмета var worldItem = itemGO.AddComponent(); - worldItem.pickupDelay = 0f; // мгновенный подбор worldItem.useFactory = false; // Тестовые данные @@ -101,8 +100,8 @@ public class InventorySceneSetup testItem.type = ItemType.Material; testItem.maxStack = 64; - worldItem.itemData = testItem; - worldItem.amount = 5; + // Используем Setup чтобы инициализировать визуал и включить мгновенный подбор + worldItem.Setup(testItem, 5); // Коллайдер для подбора (trigger для обычных коллайдеров) var box = itemGO.AddComponent(); @@ -141,6 +140,15 @@ public class InventorySceneSetup canvas.sortingOrder = 100; canvasGO.AddComponent(); + // Ensure EventSystem exists for UI interaction + var existingES = GameObject.FindObjectOfType(); + if (existingES == null) + { + var es = new GameObject("EventSystem"); + es.AddComponent(); + es.AddComponent(); + } + // Создаём панель инвентаря var inventoryPanel = CreatePanel(canvasGO.transform, "InventoryPanel", new Color(0.15f, 0.15f, 0.15f, 0.95f)); var inventoryRect = inventoryPanel.GetComponent(); diff --git a/Assets/charecter-controller/scripts/PlayerInput.cs b/Assets/charecter-controller/scripts/PlayerInput.cs new file mode 100644 index 0000000..b6558d4 --- /dev/null +++ b/Assets/charecter-controller/scripts/PlayerInput.cs @@ -0,0 +1,79 @@ +using UnityEngine; +using System; + +public class PlayerInput : MonoBehaviour +{ + public static PlayerInput Instance { get; private set; } + + // Continuous axes + public float MouseX { get; private set; } + public float MouseY { get; private set; } + public float Horizontal { get; private set; } + public float Vertical { get; private set; } + + // Continuous states + public bool Crouch { get; private set; } + public bool Run { get; private set; } + + // Events for discrete actions + public event Action OnToggleInventory; + public event Action OnDropPressed; + public event Action OnPickupPressed; + public event Action OnJumpPressed; + public event Action OnHotbarSelect; + + public bool Enabled { get; set; } = true; + + void Awake() + { + if (Instance == null) + { + Instance = this; + DontDestroyOnLoad(gameObject); + } + else + { + Destroy(gameObject); + } + } + + void Update() + { + // Always allow toggle inventory (Tab/Escape) even when input is disabled + if (Input.GetKeyDown(KeyCode.Tab) || Input.GetKeyDown(KeyCode.Escape)) + OnToggleInventory?.Invoke(); + + if (!Enabled) return; + + // Axes + MouseX = Input.GetAxis("Mouse X"); + MouseY = Input.GetAxis("Mouse Y"); + Horizontal = Input.GetAxisRaw("Horizontal"); + Vertical = Input.GetAxisRaw("Vertical"); + + // Continuous keys + Crouch = Input.GetKey(KeyCode.C); + Run = Input.GetKey(KeyCode.LeftShift); + + // Discrete actions + if (Input.GetButtonDown("Jump")) + OnJumpPressed?.Invoke(); + + if (Input.GetKeyDown(KeyCode.Tab)) + OnToggleInventory?.Invoke(); + + if (Input.GetKeyDown(KeyCode.Q)) + OnDropPressed?.Invoke(); + + if (Input.GetKeyDown(KeyCode.E)) + OnPickupPressed?.Invoke(); + + for (int i = 0; i < 9; i++) + { + if (Input.GetKeyDown(KeyCode.Alpha1 + i)) + { + OnHotbarSelect?.Invoke(i); + } + } + } +} diff --git a/Assets/charecter-controller/scripts/PlayerInput.cs.meta b/Assets/charecter-controller/scripts/PlayerInput.cs.meta new file mode 100644 index 0000000..1b89b3a --- /dev/null +++ b/Assets/charecter-controller/scripts/PlayerInput.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: cb5fd82e043d6694e90df66d2b3f267a \ No newline at end of file diff --git a/Assets/charecter-controller/scripts/charecter.cs b/Assets/charecter-controller/scripts/charecter.cs index a80766c..3315af0 100644 --- a/Assets/charecter-controller/scripts/charecter.cs +++ b/Assets/charecter-controller/scripts/charecter.cs @@ -31,6 +31,7 @@ public class charecter : MonoBehaviour float _headYaw; float _pitch; Quaternion _headBindPose; + bool _jumpRequested = false; // Animator parameter hashes — no hardcoded strings at runtime static readonly int HashSpeed = Animator.StringToHash("Speed"); @@ -49,22 +50,28 @@ public class charecter : MonoBehaviour _bodyYaw = transform.eulerAngles.y; _headYaw = _bodyYaw; _headBindPose = head.localRotation; + + // Ensure PlayerInput exists and subscribe to events + if (PlayerInput.Instance == null) + { + var go = new GameObject("PlayerInput"); + go.AddComponent(); + } + + PlayerInput.Instance.OnPickupPressed += () => TryPickupNearbyItem(); + PlayerInput.Instance.OnJumpPressed += () => { _jumpRequested = true; }; } void Update() { HandleLook(); HandleMovement(); - HandlePickup(); } // ── Item Pickup ─────────────────────────────────────────────────────────── void HandlePickup() { - if (Input.GetKeyDown(KeyCode.E)) - { - TryPickupNearbyItem(); - } + // Input moved to PlayerInput events } void TryPickupNearbyItem() @@ -115,19 +122,24 @@ public class charecter : MonoBehaviour // ── Mouse look ──────────────────────────────────────────────────────────── void HandleLook() { - _headYaw += Input.GetAxis("Mouse X") * mouseSensitivity; - _pitch -= Input.GetAxis("Mouse Y") * mouseSensitivity; + var input = PlayerInput.Instance; + if (input != null) + { + _headYaw += input.MouseX * mouseSensitivity; + _pitch -= input.MouseY * mouseSensitivity; + } _pitch = Mathf.Clamp(_pitch, -maxPitch, maxPitch); } // ── Movement ────────────────────────────────────────────────────────────── void HandleMovement() { - float h = Input.GetAxisRaw("Horizontal"); - float v = Input.GetAxisRaw("Vertical"); + var input = PlayerInput.Instance; + float h = input != null ? input.Horizontal : Input.GetAxisRaw("Horizontal"); + float v = input != null ? input.Vertical : Input.GetAxisRaw("Vertical"); - bool isCrouching = Input.GetKey(KeyCode.C); - bool isRunning = Input.GetKey(KeyCode.LeftShift) && !isCrouching; + bool isCrouching = input != null ? input.Crouch : Input.GetKey(KeyCode.C); + bool isRunning = input != null ? input.Run && !isCrouching : Input.GetKey(KeyCode.LeftShift) && !isCrouching; bool isMoving = (h * h + v * v) > 0.01f; float speed = isCrouching ? crouchSpeed : isRunning ? runSpeed : walkSpeed; @@ -147,11 +159,12 @@ public class charecter : MonoBehaviour { if (_verticalVelocity < 0f) _verticalVelocity = -2f; - if (Input.GetButtonDown("Jump") && !isCrouching) + if (_jumpRequested && !isCrouching) { _verticalVelocity = Mathf.Sqrt(jumpHeight * -2f * gravity); _anim?.SetTrigger(HashJump); } + _jumpRequested = false; } _verticalVelocity += gravity * Time.deltaTime;