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 twmanar · Aug 25, 2014 at 04:47 PM · arraysaveinventorynew

Save an array to file

Hi i need help to save my game. I've searched so much but i haven't found anything or it could be that im searching for the wrong things Oh well, the problem is i need to save my inventory[] array which store itemIds like inventory[1] is itemid 1 and that means i got it in my inventory. here is the script i'm using, which i also found somewhere around here. I'm quite new to programming and there is alot i don't understand but if you could tell me what i'm doing wrong or how to fix it i would be very glad!. Inventory.things[] is an array copied array of inventory[], i think atleast.. well the last part of the inventory script will be in the end of the post.

 using UnityEngine;
 using System.Collections;
 using System.Text;
 using System.IO;
 using System.Runtime.Serialization.Formatters.Binary;
 using System;
 using System.Runtime.Serialization;
 using System.Reflection;
 
     [Serializable]
 public class SaveData : ISerializable {
     public bool foundGem1 = false;
     public float Hp = 0;
     public float PlayerMoney = 0;
     public static string theTime =  System.DateTime.Now.ToString("hh:mm:ss");
     public static string theDate = System.DateTime.Now.ToString("MM/dd/yyyy");
     public int[] thinglist = new int[100];
     int test ;
 
     // The default constructor. Included for when we call it during Save() and Load()
     public SaveData () {}
     
     // This constructor is called automatically by the parent class, ISerializable
     // We get to custom-implement the serialization process here
     public void timeSave()
     {
         theTime = System.DateTime.Now.ToString("hh:mm:ss"); 
         theDate = System.DateTime.Now.ToString("MM/dd/yyyy");
     }
     public void Incluce ()
     {
         Hp = PlayerHp.curHealth;
         PlayerMoney = Inventory.money;
     
     }
     public SaveData (SerializationInfo info, StreamingContext ctxt)
     {
         // Get the values from info and assign them to the appropriate properties. Make sure to cast each variable.
         // Do this for each var defined in the Values section above
         foundGem1 = (bool)info.GetValue("foundGem1", typeof(bool));
         PlayerHp.curHealth = (float)info.GetValue("Hp", typeof(float)); 
         theTime = (string)info.GetValue ("Time", typeof(string));
         theDate = (string)info.GetValue("Date",typeof(string));
         Inventory.money = (int)info.GetValue("PlayerMoney", typeof(int));
         Inventory.amount = (int)info.GetValue("amount", typeof(int));
         for(int i = -1;i < Inventory.things.Length;i++)
             Inventory.things[i] = (Inventory.things[])(info.GetValue ("things" , typeof(Inventory.things[])));
         Debug.Log(Inventory.things);
         switch (Inventory.amount) 
         {
            default:
             break;
         
 
 
         }
     }
     
     // Required by the ISerializable class to be properly serialized. This is called automatically
     public void GetObjectData (SerializationInfo info, StreamingContext ctxt)
     {
         // Repeat this for each var defined in the Values section
         info.AddValue("foundGem1", (foundGem1));
         info.AddValue("Hp", PlayerHp.curHealth);
         info.AddValue("PlayerMoney", Inventory.money);
         info.AddValue ("Time", theTime);
         info.AddValue ("Date", theDate);
         info.AddValue("amount",Inventory.amount);
 
             info.AddValue  ("things", Inventory.things);
     }
 }
 
 // === This is the class that will be accessed from scripts ===
 public class SaveLoad {
 
 
 
 
 
     public static string currentFilePath ="SaveData.sav"; //SaveData.theDate + " "+ SaveData.theTime + ".sav"; //"SaveData.sav" ; // Edit this for different save files
 
     private string GetUniqueName(string name, string folderPath)
     {
         folderPath = "Game";
         name = "SaveData";
          string validatedName = name;
         int tries = 1;
         while (File.Exists(folderPath + validatedName))
         {
             validatedName = string.Format("{0} [{1}]", name, tries++);
         }
 
         return validatedName;
 //        currentFilePath = validatedName;
     }
     // Call this to write data
     public static void Save () // Overloaded
     {
         Save (currentFilePath);
     }
     public static void Save (string filePath)
     {
         SaveData data = new SaveData ();
         
         Stream stream = File.Open(filePath, FileMode.Create);
         BinaryFormatter bformatter = new BinaryFormatter();
         bformatter.Binder = new VersionDeserializationBinder();
         bformatter.Serialize(stream, data);
         stream.Close();
     }
     
     // Call this to load from a file into "data"
     public static void Load () { Load(currentFilePath); } // Overloaded
     public static void Load (string filePath)
     {
         SaveData data = new SaveData ();
         Stream stream = File.Open(filePath, FileMode.Open);
         BinaryFormatter bformatter = new BinaryFormatter();
         bformatter.Binder = new VersionDeserializationBinder();
         data = (SaveData)bformatter.Deserialize(stream);
         stream.Close();
         
         // Now use "data" to access your Values
     }
     
 }
 
 // === This is required to guarantee a fixed serialization assembly name, which Unity likes to randomize on each compile
 // Do not change this
 public sealed class VersionDeserializationBinder : SerializationBinder
 {
     public override Type BindToType( string assemblyName, string typeName )
     {
         if ( !string.IsNullOrEmpty( assemblyName ) && !string.IsNullOrEmpty( typeName ) )
         {
             Type typeToDeserialize = null;
             
             assemblyName = Assembly.GetExecutingAssembly().FullName;
             
             // The following line of code returns the type.
             typeToDeserialize = Type.GetType( String.Format( "{0}, {1}", typeName, assemblyName ) );
             
             return typeToDeserialize;
         }
         
         return null;
     }
 }
 
 



I know it isnt clean with all the comments and that but i have tried alot of things. Prefs is an earlier save system of the inventory but i want to it this way anyway.

Script 2:

 public static int amount;
     int items = amount;
 
     public static int[] things = new int[100];
 
 
     public void blaa()
     {
         Debug.Log("FOodkfds");
     }
     public void SaveInventory()
     {
 
     /*    foreach(Item item in inventory){
             if(item.itemID == i) return true;
             itemname = item.itemName; */
 
 
         /*for (int i = 0; i >= -1; i--)
                         things [i] = -1; */
 
 
         for (int i = 0; i < inventory.Count; i++) {        // mycket bra ide!!!!!!!!!!!!!!
             if(InventoryContains(i))
                 things[i] = i; 
          
         /*    foreach(Item item in inventory){
                 if(item.itemID == i) 
                 itemname = item.itemName
 
             int test = things[i];
             if (test == inventory[i].itemID)
             {
                 things[i] = test; 
             }  */
         
 
 
             //amount = inventory[i].itemID;
             print (amount + " amount");
             /*            items = inventory[i].itemID;
             print (inventory[i]"); */
         
                 }
         //PlayerPrefs.SetInt ("inventory " + i,inventory[i].itemID);
         PlayerPrefs.SetInt("money",money);
     }
      public    void LoadInventory()
     {
     //    for (int i = 0; i < inventory.Count; i++) { 
                     //    inventory [i] = -1 + i >= 0 ? database.items [amount] : new Item ();    
            int[] inventory = (int[]) things.Clone();//  ? database.items[i] : new Item();
         //    things.CopyTo(inventory, 0);
             
                 //}
         //    inventory[i] =  PlayerPrefs.GetInt("inventory " + i, -1) >= 0 ? database.items[PlayerPrefs.GetInt("inventory " + i)] : new Item();
         print (PlayerHp.curHealth);
         money = PlayerPrefs.GetInt("money" + money); 
 
     }    
 
 
 }
 



All answers are appreciated! :D

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 Turbine · Aug 26, 2014 at 02:37 AM

Use C#'s native XML serializer. You just need to put annotations on a few things and let it rip. There are two ways to use the serializer, the easy way and the hard way. If you find yourself taking more than an hour or two, then you're probably doing it the hard way. Your data class shouldn't be more complicated than the example below.

 [Serializable]
 public class Example
 {
 public int foo;
 public string bar;
 public int[] sam;
 
 }
Comment
Add comment · Show 1 · 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 twmanar · Aug 26, 2014 at 03:26 PM 0
Share

Hey thanks for answer, but i dont really understand how this would help? Could you please explain? I mean i got everything working expect for the inventory[] array

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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Error when trying to save inventory with array. 1 Answer

Array Overflow Problem 1 Answer

One component in Array which is a class resets itself to null. 1 Answer

How to save/load the Y-Coordinates of Instantiated Objects 1 Answer

Rotation no save to array 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