- Home /
saving data in arrays with c#..how ? ...
Hi, I'm currently building a game. To make it easier for me to design levels, I created a map builder for my self first. So, it should save the prefabs I Instatiated to map and its coordiantes with separetes arrays.
So I want to save these datas in the array so I can use them later in my game later on when ever I want.
Problem is how ? I never try to save anything in unity before.
Thank you.
Answer by legion_44 · Sep 06, 2013 at 08:51 PM
So, here you have the array and a list. The difference is you can't resize array in runtime (you can do this with list).
//Writed by Paul Ignasiak
//C#
List<Transform> listOfTransforms = new List<Transform>();
Transform[] arrayOfTransforms;
If you want to add something to array or list, just write
//Writted by Paul Ignasiak
Transform myTransform;
void myMethod()
{
listOfTransforms.Add(myTransform);
//or
arrayOfTransforms[index] = myTransform;
//index is value thats specificates what "place" we should assign myTransform to.
}
If you want to read the position:
Vector3 pos;
void myMethod()
{
pos = listOfTransforms[index].position;
//or
pos = arrayOfTransforms[index].position;
}
So, if you mean saving to file, you have to use the System.IO library. This is an example how you can use it to save names of Transforms from array.
using UnityEngine;
using System.Collections;
using System.IO;
public Transform[] myTransforms;
void saveAll()
{
StreamWriter sw = new StreamWriter(@"C:\tmp\text.txt");
foreach(Transform t in myTransforms)
{
sw.WriteLine("" + t.name);
}
sw.Close();
}
Of cource you can modify it to your preferences, and change C:\tmp\text.txt to what you want but you have to be warned of writing file in directory that no exists. To prevent that, use this code:
if(!Directory.Exists(@"directory"))
{
Directory.CreateDirectory(@"directory");
}
//The '@' symbol before the string is used to gain posibility of use "\" in string.
If you want to read them, use following code:
Transform[] myTransforms;
void loadAll()
{
StreamReader sr = new StreamReader(@"C:\tmp\text.txt")
for(int i = 0; i < myTransforms.Lenght; i++)
{
myTransforms[i].name = sr.ReadLine();
}
}
Hope that helps
Paul
Thanks but, I'm asking how to save them. I'm asking saving the arrays to use save / load or import / export
@Terena: Next time, please use a "comment" rather than an "answer" to reply to an existing question. Converted it to comment for you this time.
Your answer
Follow this Question
Related Questions
Import/Export of save file string 0 Answers
Level exporting (with video example) 1 Answer
Save and load a class 0 Answers
I need to save and load GameObjects. How do I do this? 3 Answers
Save game support, how do I load audio in a sertain time frame? 0 Answers