Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by mackelday · Nov 25, 2013 at 12:03 AM · playerprefsarraysloadinginventory

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);
     } 
 }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

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));
Comment
Add comment · Show 8 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image mackelday · Nov 25, 2013 at 02:08 PM 0
Share

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.

avatar image iwaldrop · Nov 25, 2013 at 06:22 PM 0
Share

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.

avatar image mackelday · Nov 25, 2013 at 10:30 PM 0
Share

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?);

avatar image iwaldrop · Nov 25, 2013 at 10:43 PM 0
Share

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. :)

avatar image iwaldrop · Nov 25, 2013 at 10:52 PM 0
Share

I've updated the original answer with an example of using the Save method.

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

17 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges