- Home /
SAVE OBJECTS IN ARRAY
I made a script that should save and load an array of objects but when I load all objects are given the coordinates of one. What i do wrong ?
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class SaveObjects : MonoBehaviour {
public Transform[] Object;
public string FileName = "QuickSave";
[System.Serializable]
class PaR
{
public float OPX;
public float OPY;
public float OPZ;
}
public void Save(){
BinaryFormatter bf = new BinaryFormatter();
FileStream file = new FileStream(FileName, FileMode.Create);
PaR newData = new PaR();
for(int i = 0; i < Object.Length; i++)
{
newData.OPX = Object[i].transform.position.x;
newData.OPY = Object[i].transform.position.y;
newData.OPZ = Object[i].transform.position.z;
}
bf.Serialize(file, newData);
file.Close();
}
public void Load(){
if (File.Exists(FileName)){
BinaryFormatter bf = new BinaryFormatter();
FileStream file = new FileStream(FileName, FileMode.Open,FileAccess.Read);
PaR newData1 = (PaR)bf.Deserialize(file);
for(int i = 0; i < Object.Length; i++)
{
Object[i].transform.position = new Vector3(newData1.OPX,newData1.OPY,newData1.OPZ);
}
file.Close();
}
}
void LateUpdate () {
if (Input.GetKey (KeyCode.F5))
{
Save();
}
if (Input.GetKey (KeyCode.F9))
{
Load();
}
}
}
Comment
Best Answer
Answer by NeverHopeless · Aug 19, 2015 at 11:25 AM
You are overwriting the data in a single object, so it would just keep the last value.
for(int i = 0; i < Object.Length; i++)
{
newData.OPX = Object[i].transform.position.x;
newData.OPY = Object[i].transform.position.y;
newData.OPZ = Object[i].transform.position.z;
}
You should instead make an array of PaR. Try something like this:
using System.Collections.Generic;
public void Save(){
BinaryFormatter bf = new BinaryFormatter();
FileStream file = new FileStream(FileName, FileMode.Create);
List<PaR> newDataCollection = new List<PaR>();
for(int i = 0; i < Object.Length; i++)
{
PaR newData = new PaR();
newData.OPX = Object[i].transform.position.x;
newData.OPY = Object[i].transform.position.y;
newData.OPZ = Object[i].transform.position.z;
newDataCollection.Add(newData);
}
bf.Serialize(file, newDataCollection);
file.Close();
}
In the same way you can reload your data as well.
^You have to re-write your load method as well, of course, so it accesses the newdata list.
In Load()
FileStream file = new FileStream (FileName, File$$anonymous$$ode.Create);
File$$anonymous$$ode.Create you should not create but Read.
Your answer
Follow this Question
Related Questions
What are GameTiles? 1 Answer
Find objects by one tag or another. 3 Answers
boolean issue 1 Answer
Add custom properties to Objects 1 Answer
Convert Object[] to List 3 Answers