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*;*
  •  		}*
    
  •  	}*
    

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?

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

}

//or the same with data.UniqueID like this

for (int i = 0; i < data.UniqueID.Count; i++) {
Debug.Log(data.UniqueID*);*
}
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)

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 2.