Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 yukizino · Aug 04, 2017 at 11:15 PM · save game

Save inventory items

So I'm working on a simple inventory system, that instantiates selected items as children of the slots GameObjects. And now I want to save those items, and all I can come up with is getting a list of the items names and saving them, as references to the items, then load them from the Resources one by one. I was wondering if there is a better way to save and load the items. Here is a glimpse of the inventory script:

                 string dir = "Slot";
                 slot [n] = GameObject.Find (dir+i).transform as RectTransform;
                 if (slot [n].GetComponentInChildren<Equip> ()) {
                     n++;
                     if (n >= slot.Length) {
                         picking = false;
                         full = true;
                     }
                 }else if (!slot [n].GetComponentInChildren<Equip> ()) {

                     ToEquip = true;
                     ToPickUp = false;
                         GameObject go = Instantiate (items, new Vector3 (0, 0, 0), slot [n].transform.rotation) as GameObject;
                         go.transform.parent = slot [n];
                         go.transform.localPosition = new Vector3 (0, 0, 0f);
                     


                         TextTarget = slot [n].GetComponentInChildren<Text> ();
                         TextTarget.text = name;
                         Destroy (gameObject);
                         Debug.Log ("Item Added To inventory");
                 }
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

2 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by Axtrainz · Aug 05, 2017 at 01:37 AM

Whenever I need to save objects such as list or any kind of collection I use [Serializable] tag on a class and save it with Binary Format. Example:

 using System.IO;
 using System.Runtime.Serialization.Formatters.Binary;
 using System;
 using UnityEngine;
 
  public class SaveInventory
  {
     public List<Item> inventory = new List<Item>();
  
     //To save inventory to file. Use static for quick access
     private void save()
     {
         BinaryFormatter bf = new BinaryFormatter();
         FileStream file = File.Create(Application.persistentDataPath + "/Inventory.dat");
         Inventory toSaveInventory = new Inventory();
 
         toSaveInventory.inventory = this.inventory;
 
         bf.Serialize(file, inventory);
         file.Close();
     }
 
     //To load inventory from file. Use static modifier for quick access
     private void load()
     {
         if (File.Exists(Application.persistentDataPath + "/Inventory.dat"))
         {
             BinaryFormatter bf = new BinaryFormatter();
             FileStream file = File.Open(Application.persistentDataPath + "/Inventory.dat", FileMode.Open);
             Inventory InventoryLoaded = (Inventory)bf.Deserialize(file);
             file.Close();
 
             this.inventory = InventoryLoaded.inventory;
         }//if
         
     }//load function
         
     //To load inventory from file with returns. Use static modifier for quick access
     private List<Item> load()
     {
         if (File.Exists(Application.persistentDataPath + "/Inventory.dat"))
         {
             BinaryFormatter bf = new BinaryFormatter();
             FileStream file = File.Open(Application.persistentDataPath + "/Inventory.dat", FileMode.Open);
             Inventory InventoryLoaded = (Inventory)bf.Deserialize(file);
             file.Close();
 
             return InventoryLoaded.inventory;
         }//if
         return new List<Item>();
     }//load function
     
 }//class
     
 [Serializable]
 class Inventory
 {
     //save a list of *item* type. this can be string, int and all type of data, See List<T> documentations C# or (Java if it helps). 
     public List<Item> inventory;
 }

Notes: Make sure your inventory to save has the same values of the saved one before saving it. I'll leave you that as homework.

Regards.

Comment
Add comment · Show 5 · 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 Beyond_Art · Dec 25, 2017 at 04:55 PM 0
Share

hi, how can I create this save system?

[Item.cs] using UnityEngine;

[CreateAsset$$anonymous$$enu] public class Item : ScriptableObject { public Sprite sprite; public GameObject gameObject; public string interactable; } /**/ [Inventory.cs]

using UnityEngine; using UnityEngine.UI;

public class Inventory : $$anonymous$$onoBehaviour { public Image[] itemImages = new Image[numItemSlots]; public GameObject[] itemGameObjects = new GameObject[numItemSlots]; public Item[] items = new Item[numItemSlots]; public string[] itemIntercatable = new string[numItemSlots]; public SaveInventory saveInventory = new SaveInventory();

 public const int numItemSlots = 8; 
 private Interactable interactable;
 public Button button;

 public void AddItem(Item itemToAdd)
 {
     for (int i = 0; i < items.Length; i++)
     {
         if (items [i] == null)
         {
             items [i] = itemToAdd;
             itemImages [i].sprite = itemToAdd.sprite;
             itemGameObjects [i] = itemToAdd.gameObject;
                             itemIntercatable[i] = itemToAdd.interactable;
                             saveInventory.items[i] = itemToAdd;
                             saveInventory.save();
                             itemImages [i].enabled = true;
                             return;
         }
     }
 }

 public void RemoveItem(Item itemToRemove)
 {
     for (int i = 0; i < items.Length; i++)
     {
         if (items [i] == itemToRemove) 
         {
             items [i] = null;
             itemImages [i].sprite = null;
             itemGameObjects [i] = null;
                             itemIntercatable[i] = null;
                             itemImages [i].enabled = false;
             return;
         }
     }
 }

}

avatar image Axtrainz Beyond_Art · Dec 25, 2017 at 07:10 PM 0
Share

Hi, As there is only a save/load function you can do add/remove/change functions.

as Example: on SaveInventory Class add the following..

 //to add new Item
 public void addItem(Item item)
 {
     // syncronize file with current inventory object. 
     //after checking if everything is syncronized..
     //addItem
     inventory.add(item);
     save(); // to re syncronize files and objects.
 }
 
 //To Remove an Item
 public bool addItem(string itemId)
 {    
     // syncronize file with current inventory object. 
     //after checking if everything is syncronized..
     //remove Item with linear search - Binary search is recommended.
     int index = 0;
     foreach(Item item in inventory)
         if(item.id == itemId)
         {    
             //we get the item by unique id.
             index = inventory.IndexOf(item); // we get index of the matching item to avoid the duplicate items.
             inventory.RemoveAt(index)
             save(); // to re syncronize files and objects.
             return true;
         }
     
     return false;
 }

These are examples for add, remember to put as [Serializable] the Item Class. if need something else contact me. Regards

avatar image Beyond_Art · Dec 25, 2017 at 08:52 PM 0
Share

Can i have your email?

avatar image Axtrainz Beyond_Art · Dec 25, 2017 at 09:25 PM 0
Share

sure guilei4910@yahoo.com

avatar image haruna9x Beyond_Art · Dec 26, 2017 at 12:37 AM 0
Share

Better if you post it as a comment. Note: [Serializable] does not support inheritance, polymorphism.

avatar image
1

Answer by agray427 · Jan 15, 2018 at 05:53 PM

I just finished writing a post on my blog that talks about serializing Item data and supports polymorphism. I recommend checking it out as a solution for your stuff as well. It also talks about the importance of separating data from the interface which will definitely help with serializing. https://graymattertutorials.wordpress.com/2018/01/15/serialization-with-json-net-in-unity-3d/

Comment
Add comment · 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

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

71 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 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 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 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 avatar image avatar image avatar image

Related Questions

Create an autosave/checkpoint feature for my game? 1 Answer

Save Game Folder 1 Answer

How to save some integers and bools when a scene is switched. 0 Answers

Persistent data, Save file doesn't come out as hoped 1 Answer

How to make an update file function for app updates? 0 Answers


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