0% found this document useful (0 votes)
18 views14 pages

Blank

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views14 pages

Blank

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Help me fix this problem.

I am using these scripts (added below) to save and load the items
from each container by assigning an id for each container. However, when containers are
stored in player inventory, and respawned in the game by dropping it from player
inventory, a new id is assgined, and the one originally stored is not preserved. It should
either assign the id that corresponds to the list of items from that container, or containers
should move between inventories retaining their id throughout. What do you suggest?

These are the scripts I am using for itemData, itemDataBase, ContainerInventoryManager,


ContainerSaveManager.

"using UnityEngine;

[CreateAssetMenu(fileName = "NewItem", menuName = "Inventory/Item")]

public class ItemData : ScriptableObject

[Header("Item Information")]

public string itemName; // Name of the item

public string category; // Category (e.g., Tools, Materials)

public string description; // Description for UI

public Sprite icon; // Icon for UI

public GameObject prefab; // World prefab for spawning/dropping

public float weight; // Weight of the item

[Header("Custom Actions")]

public CustomAction[] customActions; // List of custom actions for this item

[System.Serializable]

public class CustomAction

[Tooltip("Name of the action to display on the button")]


public string actionName;

[Tooltip("Select the type of action to perform")]

public ActionType actionType; // Action type selected in the Inspector

public enum ActionType

None,

Store,

Examine,

Use,

Drop,

Open

[System.Serializable]

public class ItemEntry

public ItemData itemData; // Reference to the item

public int quantity; // Quantity of the item

"

"using System.Collections.Generic;

using UnityEngine;

[CreateAssetMenu(fileName = "ItemDatabase", menuName = "Inventory/ItemDatabase")]


public class ItemDatabase : ScriptableObject

[Header("All Items in the Game")]

public List<ItemData> allItems;

private Dictionary<string, ItemData> itemDictionary;

private void OnEnable()

// Build the dictionary for fast lookups

itemDictionary = new Dictionary<string, ItemData>();

foreach (var item in allItems)

if (!itemDictionary.ContainsKey(item.itemName)) // Use a unique identifier

itemDictionary.Add(item.itemName, item);

else

Debug.LogWarning($"Duplicate item name detected: {item.itemName}. Item will be


skipped.");

public ItemData GetItemByID(string itemName)

{
if (itemDictionary != null && itemDictionary.TryGetValue(itemName, out var item))

return item;

Debug.LogWarning($"Item with name '{itemName}' not found in the database.");

return null;

}"

"using System.Collections.Generic;

using UnityEngine;

[System.Serializable]

public class ContainerSaveData

public string containerID;

public List<ItemSaveData> inventoryItems;

[System.Serializable]

public class ItemSaveData

public string itemID;

public int quantity;

public class ContainerSaveManager : MonoBehaviour


{

public static ContainerSaveManager Instance;

private Dictionary<string, ContainerSaveData> savedContainers = new Dictionary<string,


ContainerSaveData>();

private void Awake()

// Ensure there's only one instance of the save manager

if (Instance == null)

Instance = this;

DontDestroyOnLoad(gameObject);

else

Destroy(gameObject);

// Save container data

public void SaveContainer(ContainerInventoryManager container)

if (container == null) return;

// Get the container's save data and store it in the dictionary

var saveData = container.SaveContainerData();

savedContainers[saveData.containerID] = saveData;
Debug.Log($"Container {saveData.containerID} saved with
{saveData.inventoryItems.Count} items.");

// Load container data

public void LoadContainer(ContainerInventoryManager container, ItemDatabase


itemDatabase)

if (container == null || itemDatabase == null) return;

if (savedContainers.TryGetValue(container.containerID, out ContainerSaveData saveData))

container.LoadContainerData(saveData, itemDatabase);

Debug.Log($"Container {saveData.containerID} loaded with


{saveData.inventoryItems.Count} items.");

else

Debug.LogWarning($"No save data found for container {container.containerID}.");

// Optional: Save all data to persistent storage (e.g., JSON, PlayerPrefs)

public void SaveAllData()

Debug.Log("All container data saved.");

// Implement serialization here

}
// Optional: Load all data from persistent storage

public void LoadAllData()

Debug.Log("All container data loaded.");

// Implement deserialization here

}"

"using System;

using System.Collections.Generic;

using UnityEngine;

[System.Serializable]

public class InitialItem

public ItemData item;

public int quantity;

public class ContainerInventoryManager : MonoBehaviour

[Header("Container Settings")]

public float maxStorageCapacity;

[Header("Initial Items")]

public List<InitialItem> initialItems;

private Dictionary<ItemData, int> containerInventory = new Dictionary<ItemData, int>();


private float currentWeight = 0f;

[Header("UI")]

private UIManager uiManager;

private bool isContainerOpen;

public string containerID;

private void Start()

// Assign a unique ID to this container if it doesn't already have one

if (string.IsNullOrEmpty(containerID))

containerID = Guid.NewGuid().ToString();

// Initialize items (for new containers, not restored ones)

foreach (var initialItem in initialItems)

AddItemToContainer(initialItem.item, initialItem.quantity, false);

// Locate UIManager if not already assigned

if (uiManager == null)

uiManager = FindObjectOfType<UIManager>();

if (uiManager == null)

{
Debug.LogWarning("UIManager not found in the scene. UI will not update.");

// Attempt to load data if it exists

var saveManager = ContainerSaveManager.Instance;

if (saveManager != null)

saveManager.LoadContainer(this, FindObjectOfType<ItemDatabase>());

else

Debug.LogWarning("ContainerSaveManager instance not found. Containers will not


persist between sessions.");

public bool AddItemToContainer(ItemData item, int quantity = 1, bool refreshUI = true)

if (item == null || quantity <= 0) return false;

float itemTotalWeight = item.weight * quantity;

if (currentWeight + itemTotalWeight > maxStorageCapacity)

Debug.LogWarning($"Cannot add {item.itemName}. Weight limit exceeded.");

return false;

}
if (containerInventory.ContainsKey(item))

containerInventory[item] += quantity;

else

containerInventory[item] = quantity;

currentWeight += itemTotalWeight;

if (refreshUI)

UpdateUI();

Debug.Log($"Added {quantity} of {item.itemName} to container {containerID}");

return true;

public void RemoveItemFromContainer(ItemData item, int quantity = 1, bool refreshUI =


true)

if (item == null || !containerInventory.ContainsKey(item)) return;

int currentQuantity = containerInventory[item];

int quantityToRemove = Mathf.Min(quantity, currentQuantity);

containerInventory[item] -= quantityToRemove;

if (containerInventory[item] <= 0)
{

containerInventory.Remove(item);

currentWeight -= item.weight * quantityToRemove;

if (refreshUI && isContainerOpen)

UpdateUI();

Debug.Log($"Removed {quantityToRemove} of {item.itemName} from container


{containerID}");

public void StoreItemToPlayer(ItemData itemData, PlayerInventory playerInventory)

if (itemData == null || playerInventory == null) return;

// Remove item from the container

RemoveItemFromContainer(itemData, 1);

// Add item to the player's inventory

playerInventory.AddItem(itemData);

// Update UI

UpdateUI();

// Hide side panel if item is no longer in the container

if (!containerInventory.ContainsKey(itemData) && uiManager != null)

uiManager.sidePanel.SetActive(false);
}

private void UpdateUI()

if (uiManager == null) return;

uiManager.storageCapacityText.text = $"Capacity: {currentWeight:F2} /


{maxStorageCapacity:F2}";

uiManager.PopulateItemList(this);

public Dictionary<ItemData, int> GetInventoryList()

return new Dictionary<ItemData, int>(containerInventory);

public float GetCurrentWeight()

return currentWeight;

public ContainerSaveData SaveContainerData()

var saveData = new ContainerSaveData

containerID = containerID,

inventoryItems = new List<ItemSaveData>()

};
foreach (var kvp in containerInventory)

saveData.inventoryItems.Add(new ItemSaveData

itemID = kvp.Key.name, // Using 'name' as itemID must be unique

quantity = kvp.Value

});

return saveData;

public void LoadContainerData(ContainerSaveData saveData, ItemDatabase itemDatabase)

if (saveData == null || itemDatabase == null) return;

containerID = saveData.containerID;

containerInventory.Clear();

currentWeight = 0f;

foreach (var itemData in saveData.inventoryItems)

ItemData item = itemDatabase.GetItemByID(itemData.itemID);

if (item != null)

AddItemToContainer(item, itemData.quantity, false);

}
}

UpdateUI();

private void OnDestroy()

// Save this container's data when destroyed (if desired)

var saveManager = ContainerSaveManager.Instance;

if (saveManager != null)

saveManager.SaveContainer(this);

}"

You might also like