Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 11 Next capture
2021 2022 2023
1 capture
11 Jun 22 - 11 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 Worempie · Jul 06, 2015 at 02:48 PM · gameobjectsaveload

Saving and Loading Data with a for loop

HI,

I have a question about loading your data. I've managed to extract a random ID number from gameObjects and store them in a file:

         for (int i = 0; i < characterIDList.Count; i++) {
             data.UniqueID = characterIDList;
             Debug.Log(data.UniqueID[0]);
             Debug.Log(data.UniqueID[1]);
             }

but when loading I have a problem. It needs to get the list of gameobjects from the List characters and apply the stored data from the data.List UniqueID onto them. This is the code I have in the load function:

 for(int y = 0; y < characters.Count; y++){
     
                     for(int i = 0; i < data.UniqueID.Count; i++)
                     {
                         characters[y].GetComponent<EntityScript>().characterID = data.UniqueID[i];
                     }
                 }
 

It changes all the charactersID's to the same value. How do i do it so that they all get their correct ID's back?

Comment
Add comment · Show 6
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 Cherno · Jul 06, 2015 at 03:02 PM 0
Share

Please explain what this piece of code is supposed to do, specifically why you iterate through the list but assign the whole list to data.UniqueID with each iteration.

 for (int i = 0; i < characterIDList.Count; i++) {
              data.UniqueID = characterIDList;
              Debug.Log(data.UniqueID[0]);
              Debug.Log(data.UniqueID[1]);
              }
avatar image Worempie · Jul 06, 2015 at 03:28 PM 0
Share

Every GameObject with the EntityScript attached will give his personal ID to the characterIDList. When I exit the scene or click on the save button I want to copy all the strings from the characterIDList to the data.UniqueID string list.

avatar image barbe63 · Jul 06, 2015 at 04:22 PM 1
Share

Cherno is right. You are making an iteration but never use it. It should be something more like:

  for (int i = 0; i < characterIDList.Count; i++) {
               data.UniqueID[i] = characterIDList[i];
 }

But seeing only that part of the code it's hard to tell you how exactly it should be.

avatar image Worempie · Jul 06, 2015 at 07:55 PM 0
Share

Here is the full code. Some of it might not work since I didn't really test it yet. Every single Gameobject with EntityScript add himself to the characters and characterIDList.:`

using UnityEngine; using System.Collections; using System; using System.Runtime.Serialization.Formatters.Binary; using System.IO; using System.Collections.Generic;

[Serializable] public class GameSettings : $$anonymous$$onoBehaviour {

 public static GameSettings control;
 public GameObject player; //for finding the player gameobject
 public Vector3 playerPosition; //for getting the players position
 public static List<GameObject> characters;// = new List<GameObject> (); //getting all the characters
 public static List<string> characterIDList;// = new List<string>(); //for setting the character ID

 //creating a list of letters and numbers for a unique ID list
 private static string[] idIdentifier = new string[] {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
     "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
     "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6",
     "7", "8", "9"};

 //creating an Array with all possible ID's
 private static ArrayList uniqueIDList = new ArrayList();

 void Start(){
     characters = new List<GameObject> ();
     characterIDList = new List<string> ();
 }

 void Update(){
     if (control == null) {
         DontDestroyOnLoad (this);
         control = this;
     } 
     else if (control != this) {
         Destroy(gameObject);
     }
 }



 public void SaveData(){
     BinaryFormatter bf = new BinaryFormatter ();
     FileStream file = File.Create (Application.persistentDataPath + "/playerinfo.dat");
 
     PlayerData data = new PlayerData ();

     for (int i = 0; i < characterIDList.Count; i++) {
         data.UniqueID = characterIDList;
         Debug.Log(data.UniqueID[0]);
         Debug.Log(data.UniqueID.Count);
         Debug.Log(characterIDList.Count);
         }

     bf.Serialize (file, data);
     file.Close ();
 }

 public void LoadData(){
     if (File.Exists (Application.persistentDataPath + "/playerinfo.dat")) {
         BinaryFormatter bf = new BinaryFormatter();
         FileStream file = File.Open(Application.persistentDataPath + "/playerinfo.dat", File$$anonymous$$ode.Open);
         PlayerData data = (PlayerData)bf.Deserialize(file);

         characterIDList = data.UniqueID;

         for(int i = 0; i < characters.Count; i++){
             characters[i].GetComponent<EntityScript>().characterID = characterIDList[i];
         }

         file.Close();
     }
 }

 public static string getID() {
     string uniqueID;
     do{
         uniqueID = "";
         for(int i = 0; i < 8; i++) {
             uniqueID += idIdentifier[UnityEngine.Random.Range(0, idIdentifier.Length)];
         } 
     } while(uniqueIDList.Contains(uniqueID));
     uniqueIDList.Add(uniqueID);
     return uniqueID;
 }

}

[Serializable] class PlayerData{ public List UniqueID = new List(); public int AmountOfCharacters; }

avatar image Cherno · Jul 06, 2015 at 09:37 PM 0
Share

Take a look at barbe63's code example and try to understand what it does.

Show more comments

2 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by barbe63 · Jul 06, 2015 at 09:57 PM

Well I would say you have many things to do:

  • Assure that characterList is not empty. I assume it's not even if you don't posted the code for how you fill it.

  • make the UniqueID a string list so it would match the characterList type.

  • set the UniqueId list outside the loop. A single command would work.

    data.UniqueID = new List(characterIDList); // copy

or

 data.UniqueID = characterIDList; // reference

  • you can still use a for loop for debugging purpose only like this:

        for (int i = 0; i < characterIDList.Count; i++) {
              Debug.Log(characterIDList[i]);
              }
     
     //or the same with data.UniqueID like this
     
      for (int i = 0; i < data.UniqueID.Count; i++) {
              Debug.Log(data.UniqueID[i]);
              }
    
    

Your Loading function seems better than the one you posted with the y. Which I understand now why it would always give the same value to all your characters. (giving the last value of the i iteration)

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

Answer by Voxel-Busters · Aug 08, 2015 at 06:32 PM

Simpler solution would be to directly serialize MonoBehaviour component, which internally saves all the essential properties. But MonoBehaviour serialization wont be possible using Binary Formatter.

But its possible using Runtime Serialization for Unity. Its not just another serialization plugin which works only on custom c# objects. But what makes it special is its capablity to serialize Unity Objects like GameObject, MonoBehaviours, Textures, Prefabs etc. As a matter of fact, you can even use it for Scene Serialization. For more info about supported list, please check this link.

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Save/Load Objects settings(position, rotation ...) 1 Answer

Hard question about saving and loading 1 Answer

Saving and Loading and assinging to gameobject 0 Answers

Serialize GameObject 1 Answer

Save Multiple GameObject with XML 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