One of the most common inventory features in games is the ability for players to interact with containers in the game world - like chests, backpacks, or storage lockers. This guide explains how to implement this functionality using Ultimate Grid Inventory's Environment Container Holder component.
Here's a complete example of how to implement container interaction in your game:
using UnityEngine;using Inventory.Scripts.Core.MonoBehaviours;public class ContainerInteraction : MonoBehaviour{ [SerializeField] private EnvironmentContainerHolder containerHolder; [SerializeField] private float interactionDistance = 2f; private Camera mainCamera; private bool isInRange = false; private void Start() { mainCamera = Camera.main; // Optional: Add a visual indicator that this object is interactive if (TryGetComponent<Renderer>(out var renderer)) { // You could add an outline shader or highlight effect here } } private void Update() { // Check if player is in range of the container CheckPlayerDistance(); // Handle interaction input if (isInRange && Input.GetKeyDown(KeyCode.E)) { // Toggle the container open/closed containerHolder.ToggleEnvironmentContainer(); // Optional: Play sound effect if (containerHolder.IsOpen) { // Play open sound Debug.Log("Container opened"); } else { // Play close sound Debug.Log("Container closed"); } } } private void CheckPlayerDistance() { // Simple distance check - you might want to use raycasting or other methods float distance = Vector3.Distance(transform.position, Camera.main.transform.position); isInRange = distance <= interactionDistance; // Optional: Show interaction prompt when in range if (isInRange) { // Display "Press E to open" UI prompt } }}
To persist container contents between game sessions:
Create a unique identifier for each container in your game world
When saving the game, store the contents of each container's inventory
When loading, restore the items to the appropriate container inventories
For a comprehensive guide to saving and loading inventory data, see the Save System documentation.
// Example save methodpublic void SaveContainerContents(string containerId, EnvironmentContainerHolder container, SaveStrategySo saveStrategy){ // Get the container item var containerItem = container.GetItemEquipped(); if (containerItem != null && containerItem.InventoryMetadata is ContainerMetadata metadata) { // Get all items from the container var items = metadata.GetAllItems(); // Convert items to JSON and save string jsonData = JsonInventoryUtility.GetJson(items); saveStrategy.Save(containerId, jsonData); }}
Create container types with different appearances and capacities
Add sound effects for opening, closing, and locking containers
Implement trapped containers that trigger effects when opened
By following this guide, you'll create interactive containers that seamlessly integrate with the Ultimate Grid Inventory system, allowing players to store and retrieve items throughout your game world.