Download Assets/Scripts/Inventory/InventoryManager.cs from AliAch/my-unity-assets: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/datasets/AliAch/my-unity-assets/resolve/main/Assets/Scripts/Inventory/InventoryManager.cs
- Command line
-
hf download hf://datasets/AliAch/my-unity-assets/Assets/Scripts/Inventory/InventoryManager.cs
-
curl -L -o InventoryManager.cs https://huggingface.co/datasets/AliAch/my-unity-assets/resolve/main/Assets/Scripts/Inventory/InventoryManager.cs
12.2 kB
| using System.Collections; | |
| using System.Collections.Generic; | |
| using UnityEngine; | |
| public class InventoryManager : MonoBehaviour | |
| { | |
| public static InventoryManager instance; | |
| [] | |
| public int lineCount = 6; // Width | |
| public int rowCount = 4; // Height | |
| public int depthCount = 3; // Depth into the bag | |
| [] | |
| public Vector3 gridOffset = new Vector3(0f, 0.25f, 0.35f); | |
| public Vector3 gridScale = new Vector3(1.75f, 1.75f, 1f); | |
| public float cellSize = 0.15f; | |
| public float gridSpacing = 0.05f; | |
| [] | |
| public Transform playerCamera; | |
| public MonoBehaviour cameraLookScript; // Generic to fit your look script | |
| public float transitionSpeed = 0.4f; | |
| [] | |
| public GameObject backpackPrefab; | |
| public Transform backpackRestPoint; | |
| public Transform inventoryLookTarget; | |
| public Vector3 backpackRotationOffset = new Vector3(0, 180, 0); | |
| public GameObject inventoryScreenUI; | |
| // Internal State | |
| private GameObject cachedBackpackObj; | |
| private GameObject gridContainer; // generate via code | |
| private bool isInventoryOpen = false; | |
| private bool isTransitioning = false; | |
| private Quaternion originalCameraLocalRot; | |
| // Grid Math Systems | |
| private InventoryGrid3D grid3D; | |
| private InventoryPlacer placer; | |
| private List<ItemData> allPhysicalItems = new List<ItemData>(); | |
| private void Awake() | |
| { | |
| instance = this; | |
| // Initialize your new Grid and Placer math system | |
| grid3D = new InventoryGrid3D(lineCount, rowCount, depthCount); | |
| placer = new InventoryPlacer(grid3D); | |
| } | |
| private void Start() | |
| { | |
| // 1. Spawn the Backpack | |
| cachedBackpackObj = Instantiate(backpackPrefab, backpackRestPoint.position, backpackRestPoint.rotation, backpackRestPoint); | |
| // 2. Automatically create the Grid Container INSIDE the backpack | |
| gridContainer = new GameObject("Inventory3DGrid"); | |
| gridContainer.transform.SetParent(cachedBackpackObj.transform); | |
| gridContainer.transform.localPosition = gridOffset; | |
| gridContainer.transform.localRotation = Quaternion.identity; | |
| gridContainer.transform.localScale = gridScale; | |
| // Hide at start | |
| cachedBackpackObj.SetActive(false); | |
| if (inventoryScreenUI != null) inventoryScreenUI.SetActive(false); | |
| } | |
| private void Update() | |
| { | |
| // Handle Tab Key to open/close | |
| if (Input.GetKeyDown(KeyCode.Tab) && !isTransitioning) | |
| { | |
| if (PickUpScript.instance != null && PickUpScript.instance.heldObj != null) return; | |
| if (isInventoryOpen) CloseInventory(); | |
| else OpenInventory(); | |
| } | |
| } | |
| public void AddToInventory(GameObject itemObj) | |
| { | |
| ItemData itemData = itemObj.GetComponent<ItemData>(); | |
| if (itemData == null) | |
| { | |
| Debug.LogError("Tried to add object without ItemData to inventory!"); | |
| return; | |
| } | |
| List<ItemData> reflowedItems = new List<ItemData>(); | |
| if (placer.TryPlace(itemData, reflowedItems)) | |
| { | |
| if (!allPhysicalItems.Contains(itemData)) | |
| { | |
| allPhysicalItems.Add(itemData); | |
| } | |
| UpdateItemVisuals(itemData); | |
| // --- PRINT DETAILED LOG TO CONSOLE --- | |
| LogItemPlacement(itemData); | |
| // If duplicate stacking caused an older copy to reflow/rotate, update its visuals and log it | |
| if (reflowedItems != null) | |
| { | |
| foreach (ItemData reflowed in reflowedItems) | |
| { | |
| UpdateItemVisuals(reflowed); | |
| Debug.Log($"[Reflowed Stack Item] '{reflowed.itemID}' locked to Swap State 2 at [{reflowed.gridPosition.x},{reflowed.gridPosition.y},{reflowed.gridPosition.z}]"); | |
| } | |
| } | |
| } | |
| else | |
| { | |
| Debug.LogWarning($"[Inventory] No room left for {itemObj.name} or it is too big!"); | |
| } | |
| } | |
| private void UpdateItemVisuals(ItemData itemData) | |
| { | |
| GameObject itemObj = itemData.gameObject; | |
| // 1. Ensure active & parented to grid | |
| itemObj.SetActive(true); | |
| itemObj.transform.SetParent(gridContainer.transform); | |
| // 2. Reset transforms for accurate bounds calculations | |
| itemObj.transform.localScale = Vector3.one; | |
| itemObj.transform.localRotation = Quaternion.identity; | |
| // 3. Strip Physics | |
| Rigidbody rb = itemObj.GetComponent<Rigidbody>(); | |
| if (rb != null) Destroy(rb); | |
| Collider[] colliders = itemObj.GetComponentsInChildren<Collider>(); | |
| foreach (var col in colliders) col.enabled = false; | |
| // 4. Scale: intentionally left at Vector3.one (set in step 2). Items keep their true | |
| // authored world size - a footprint of N slots should measure exactly N * cellSize, | |
| // never be scaled up/down to visually "fit". Only rotation (swap state) and position | |
| // (grid slot) change. | |
| // 5. Grid Position Calculations (Synchronized with 180� camera view) | |
| // X: Negated so Index 0 starts on Screen Left -> fills Screen Right | |
| float xPos = -((itemData.gridPosition.x - (lineCount / 2f) + (itemData.currentFootprint.x / 2f)) * (cellSize + gridSpacing)); | |
| // Y: Negated so Index 0 starts at Screen Top -> stacks Downward | |
| float yPos = -(itemData.gridPosition.y + (itemData.currentFootprint.y / 2f)) * (cellSize + gridSpacing); | |
| // Z: Z=0 is at local 0 (Front/Top Layer). Higher Z values move deeper into bag (-Z) | |
| float zPos = -itemData.gridPosition.z * (cellSize + gridSpacing); | |
| itemObj.transform.localPosition = new Vector3(xPos, yPos, zPos); | |
| // 6. Rotation based on swapState. | |
| // Model convention: Z = face axis, Y = up axis, X = side axis. | |
| // State1 (bulk moves onto X / horizontal): roll -90 deg around Z. | |
| // State2 (bulk moves onto Z / depth): pitch -90 deg around X. | |
| switch (itemData.swapState) | |
| { | |
| case 0: | |
| itemObj.transform.localRotation = Quaternion.Euler(0, 0, 0); | |
| break; | |
| case 1: | |
| itemObj.transform.localRotation = Quaternion.Euler(0, 0, -90f); | |
| break; | |
| case 2: | |
| itemObj.transform.localRotation = Quaternion.Euler(-90f, 0, 0); | |
| break; | |
| } | |
| } | |
| private void LogItemPlacement(ItemData itemData) | |
| { | |
| // Total cells occupied by the 3D volume | |
| int totalSlots = itemData.currentFootprint.x * itemData.currentFootprint.y * itemData.currentFootprint.z; | |
| List<string> occupiedCoords = new List<string>(); | |
| // Iterate through every cell occupied by the item's footprint | |
| for (int y = itemData.gridPosition.y; y < itemData.gridPosition.y + itemData.currentFootprint.y; y++) | |
| { | |
| for (int x = itemData.gridPosition.x; x < itemData.gridPosition.x + itemData.currentFootprint.x; x++) | |
| { | |
| for (int z = itemData.gridPosition.z; z < itemData.gridPosition.z + itemData.currentFootprint.z; z++) | |
| { | |
| occupiedCoords.Add($"[{x},{y},{z}]"); | |
| } | |
| } | |
| } | |
| string coordsString = string.Join("; ", occupiedCoords); | |
| // Format the console output | |
| string logMessage = $"Item name : '{itemData.itemID}',\n" + | |
| $"Slots : ({totalSlots}),\n" + | |
| $"Taken coords : {coordsString},\n" + | |
| $"Current Size : ({itemData.currentFootprint.x},{itemData.currentFootprint.y},{itemData.currentFootprint.z}) (Swap State: {itemData.swapState})"; | |
| Debug.Log(logMessage); | |
| } | |
| // --- ANIMATION & TRANSITION LOGIC --- | |
| private void OpenInventory() | |
| { | |
| isInventoryOpen = true; | |
| Cursor.lockState = CursorLockMode.None; | |
| Cursor.visible = true; | |
| originalCameraLocalRot = playerCamera.localRotation; | |
| if (cameraLookScript != null) cameraLookScript.enabled = false; | |
| StartCoroutine(TransitionInventory(true)); | |
| } | |
| private void CloseInventory() | |
| { | |
| isInventoryOpen = false; | |
| Cursor.lockState = CursorLockMode.Locked; | |
| Cursor.visible = false; | |
| StartCoroutine(TransitionInventory(false)); | |
| } | |
| private void OnDrawGizmos() | |
| { | |
| if (gridContainer == null) return; | |
| Gizmos.matrix = gridContainer.transform.localToWorldMatrix; | |
| Color[] depthColors = new Color[] | |
| { | |
| new Color(0f, 1f, 0f, 0.8f), // Z=0 : Green (Front / Top Depth Level) | |
| new Color(0f, 1f, 1f, 0.7f), // Z=1 : Cyan | |
| new Color(1f, 0.92f, 0f, 0.7f), // Z=2 : Yellow | |
| new Color(1f, 0f, 1f, 0.7f), // Z=3 : Magenta | |
| new Color(1f, 0f, 0f, 0.7f) // Z=4+: Red | |
| }; | |
| for (int z = 0; z < depthCount; z++) | |
| { | |
| Gizmos.color = depthColors[Mathf.Min(z, depthColors.Length - 1)]; | |
| for (int y = 0; y < rowCount; y++) | |
| { | |
| for (int x = 0; x < lineCount; x++) | |
| { | |
| float xPos = -((x - (lineCount / 2f) + 0.5f) * (cellSize + gridSpacing)); | |
| float yPos = -(y + 0.5f) * (cellSize + gridSpacing); | |
| float zPos = -z * (cellSize + gridSpacing); | |
| Vector3 cellCenter = new Vector3(xPos, yPos, zPos); | |
| Vector3 baseSize = new Vector3(cellSize, cellSize, cellSize); | |
| // --- THICK BORDER TRICK --- | |
| // Drawing multiple passes slightly scaled creates bold, thick wireframes | |
| Gizmos.DrawWireCube(cellCenter, baseSize); | |
| Gizmos.DrawWireCube(cellCenter, baseSize * 1.02f); | |
| Gizmos.DrawWireCube(cellCenter, baseSize * 0.98f); | |
| } | |
| } | |
| } | |
| } | |
| private IEnumerator TransitionInventory(bool opening) | |
| { | |
| isTransitioning = true; | |
| float timeElapsed = 0f; | |
| Quaternion startCamRot = playerCamera.rotation; | |
| Vector3 directionToTarget = inventoryLookTarget.position - playerCamera.position; | |
| Quaternion targetCamRot = opening ? Quaternion.LookRotation(directionToTarget) : playerCamera.parent.rotation * originalCameraLocalRot; | |
| Vector3 startModelPos = cachedBackpackObj.transform.position; | |
| Quaternion startModelRot = cachedBackpackObj.transform.rotation; | |
| Quaternion openRotation = targetCamRot * Quaternion.Euler(backpackRotationOffset); | |
| Vector3 targetModelPos = opening ? inventoryLookTarget.position : backpackRestPoint.position; | |
| Quaternion targetModelRot = opening ? openRotation : backpackRestPoint.rotation; | |
| if (opening) | |
| { | |
| cachedBackpackObj.SetActive(true); | |
| if (inventoryScreenUI != null) inventoryScreenUI.SetActive(true); | |
| } | |
| else | |
| { | |
| if (inventoryScreenUI != null) inventoryScreenUI.SetActive(false); | |
| } | |
| while (timeElapsed < transitionSpeed) | |
| { | |
| timeElapsed += Time.deltaTime; | |
| float t = timeElapsed / transitionSpeed; | |
| t = t * t * (3f - 2f * t); // Smooth easing | |
| playerCamera.rotation = Quaternion.Slerp(startCamRot, targetCamRot, t); | |
| cachedBackpackObj.transform.position = Vector3.Lerp(startModelPos, targetModelPos, t); | |
| cachedBackpackObj.transform.rotation = Quaternion.Slerp(startModelRot, targetModelRot, t); | |
| yield return null; | |
| } | |
| playerCamera.rotation = targetCamRot; | |
| cachedBackpackObj.transform.position = targetModelPos; | |
| cachedBackpackObj.transform.rotation = targetModelRot; | |
| if (!opening) | |
| { | |
| cachedBackpackObj.SetActive(false); | |
| playerCamera.localRotation = originalCameraLocalRot; | |
| if (cameraLookScript != null) cameraLookScript.enabled = true; | |
| } | |
| isTransitioning = false; | |
| } | |
| } |