- Home /
How to load an inventory array?
I am trying to use player prefs to save, and subsequently load, my player's inventory. The inventory is handled by the c# file Inventory3.cs, and saving and loading are handled in the javascript file SaveLoad2.js. My issue is that the players inventory is comprised of "Item" objects, a class in the Inventory3.cs file. How can I call the constructor for Item in my scripts below?
Thanks! Any and all advice is appreciated.
//SaveLoad2.js
#pragma strict
public static var player : GameObject;
player = GameObject.FindGameObjectWithTag("Player");
public static var invScript : Inventory3;
invScript = player.GetComponent("Inventory3");
public static var invSize : int;
invSize = invScript.invSize;
public static var slots : int[];
slots = new int[invSize];
public static function Save() {
PlayerPrefs.SetFloat ("playerX", player.transform.position.x);
PlayerPrefs.SetFloat ("playerY", player.transform.position.y);
PlayerPrefs.SetFloat ("playerZ", player.transform.position.z);
PlayerPrefs.SetInt("sceneToLoad", Application.loadedLevel);
for (var i : int = 0; i< invSize; i++) {
if (invScript.inv[i] != null) {
PlayerPrefs.SetString("InventoryItemName"+i, invScript.inv[i].name);
PlayerPrefs.SetString("InventoryItemDesc"+i, invScript.inv[i].description);
PlayerPrefs.SetInt("InventoryItemNumber"+i, invScript.inv[i].number);
PlayerPrefs.SetInt("InventoryItemUses"+i, invScript.inv[i].uses);
PlayerPrefs.SetInt("StackInv"+i, invScript.stackInv[i]);
slots[i] = 1;
}
else {
slots[i]=0;
}
}
}
public static function Load() {
Application.LoadLevel(PlayerPrefs.GetInt("sceneToLoad"));
player.transform.position = new Vector3(PlayerPrefs.GetFloat ("playerX"),PlayerPrefs.GetFloat ("playerY"), PlayerPrefs.GetFloat ("playerZ"));
for (var i : int = 0; i < invSize; i ++) {
if (slots[i] == 1) {
//Somehow populate the inventory with the other items ***********************************************************
}
}
}
//Inventory3.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Inventory3 : MonoBehaviour {
public int invSize = 10;
public Item[] inv;
public int invCount = 0;
public int[] stackInv;
public void Start() {
Item tester = new Item("tester","this is a test",1,0);
inv = new Item[invSize];
stackInv = new int[invSize];
for (int u=0; u<invSize; u++) {
inv[u] = null;
stackInv[u] = 0;
}
inv[0] = tester;
stackInv[0] = 1;
}
public void addItem(Item item) {
for (int i = 0; i < invSize; i++) {
if (inv[i] != null && inv[i].name == item.name) {
stackInv[i] += item.number;
break;
}
if (inv[i] == null) {
inv[i] = item;
stackInv[i] += item.number;
break;
}
else {
Debug.Log ("Inventory is full");
}
}
}
public void Update() {
if (Input.GetKeyUp(KeyCode.I)) {
for (int j = 0; j < invSize; j++) {
if (inv[j] != null) {
Debug.Log (j + " " + inv[j].name);
}
else {
Debug.Log ("end of inventory");
break;
}
}
}
}
}
public class Item {
public string name;
public string description;
public int number;
public int uses;
public Item(string name,string description,int number,int uses)
{
this.name = name;
this.description = description;
this.number = number;
this.uses = uses;
}
public Item makeItem(string n, string d, int num, int u) {
Item result = new Item(n, d, num, u);
return result;
}
}
public class ItemsDatabase : MonoBehaviour {
public Dictionary <string, Item> dictionary = new Dictionary<string, Item>();
public Item Apple = new Item("Apple","You should know what an apple is",1,1);
public void Start() {
dictionary.Add(Apple.name,Apple);
}
}
Answer by iwaldrop · Nov 25, 2013 at 02:28 AM
A better method might be to serialize the inventory to disk. By using the [Serializable] attribute on the Item class you can very easily save and load that array to disk.
Here's a basic serializer:
using System;
using System.IO;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
public class Serializer
{
public static T Load<T>(string filename) where T: class
{
if (File.Exists(filename))
{
try
{
using (Stream stream = File.OpenRead(filename))
{
BinaryFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(stream) as T;
}
}
catch (Exception e)
{
Debug.Log(e.Message);
}
}
return default(T);
}
public static void Save<T>(string filename, T data) where T: class
{
using (Stream stream = File.OpenWrite(filename))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, data);
}
}
}
To use it, make sure the class you're trying to serialize has the 'Serializable' attribute, then just call Save or Load with the Type and the path to the file.
[System.Serializable]
public class Item
{
// stuff here
}
Serializer.Save<Item[]>(string.Format("{0}{1}", dataPath, filename), itemArray);
inv = Serializer.Load<Item[]>(string.Format("{0}{1}", dataPath, filename));
Thanks so much! I'm still having a little trouble though. So in the my SaveLoad2 javascript file, in the save function, I would put something like Serializer.Save (string.Format("{0}{1}", invScript.inv, invSave)); ? I guess I'm a little unclear on what the datapath really is and how a serializer works.
The serializer saves your array of objects out to disk. You can call the Save method directly as I demonstrated. It kind of obsoletes your js script. :)
The datapath is where on your disk you want to save the information. Checkout Application.dataPath for more information. You could also just bake the dataPath into the script if you want. The filename is the name of the file.
Sorry for the short answer, but I'm at work right now. Let me know if you need any more help to get it working.
Ha I hope work isn't too bad. Ive gotten the Load function to compile almost exactly like you showed me, as Inventory3.inv = Serializer.Load(string.Format("{0}{1}", Application.dataPath, "invSave")); However when I try to use the save function, it tells me "error CS1501: No overload for method Save' takes1' arguments." I think it's because there is a second parameter in the save function, "T data." I've tried all sorts of things in that slot and can't get it to compile, what would you recommend?
I'm thinking Inventory3.inv = Serializer.Save(string.Format("{0}{1}", Application.dataPath, "invSave"), Something might go here?);
You have to give the method the array you're trying to save. ;)
Also, Save doesn't return anything, so don't try to assign it to anything. Lots to take in, I know. :)
I've updated the original answer with an example of using the Save method.
Your answer
Follow this Question
Related Questions
How would I use ArrayPrefs2 to track destroyed objects and/or instantiated objects? 0 Answers
Save/Load Animation State of Instantiated Prefabs 0 Answers
Saving and load from player prefs in Unity3D on mobile devices?? 0 Answers
how do I scroll thru a array 2 Answers
Problems with Playerprefs script 1 Answer