- Home /
Save customized changes to prefabs at runtime.
I have few characters in my game that the player can customize with new accessories and changing some properties on the characters like color etc. Now these characters are saved as prefab instances in my game and I know i can't make changes to prefabs and save them during runtime. So the only other option I can think of is storing the customization data into a file and save that to disk and read it during runtime to restore the changes. I wanted to know if anyone has a better solution to this problem or saving it to a file is the best way to go about it? Any help is appreciated. Thanks.
Since prefabs can't be created outside of the editor environment, the only way is indeed to sdave the relevant data and reconstruct the prefab so it reflects the changes after loading.
Cool, this is what I was exactly thinking of doing but wanted to make sure there isn't an inherent way of doing it in unity. Thanks for the reply.
Answer by toddisarockstar · Mar 24, 2016 at 05:37 AM
cherno is exactly right.
here is a read/write example stick this on all your game objects to snap them all back to positions when the game starts just an example to build on. it saves positions with spacebar
#pragma strict
import System.IO;
import System.Text.RegularExpressions;
import System.Diagnostics;
var saves:String;
var rd:String;
var posarray:String[];
var savefolder:String;
savefolder=Application.dataPath;
saves =savefolder+"/"+gameObject.name+".txt";
print(saves);
if(!System.IO.Directory.Exists(savefolder)){
System.IO.Directory.CreateDirectory(savefolder);}
var readsave :StreamReader = new StreamReader(saves);
var txt:String;
var p:Vector3;
if(File.Exists(saves)){
readsave = new StreamReader(saves);
rd = readsave.ReadToEnd();
readsave.Close();
posarray=rd.Split(","[0]);
float.TryParse(posarray[0],p.x);
float.TryParse(posarray[1],p.y);
float.TryParse(posarray[1],p.z);
transform.position=p;
}
function Update(){
if(Input.GetKeyDown("space")){
if(File.Exists(saves)){File.Delete(saves);}
var swreg2 : StreamWriter = new StreamWriter(saves);
txt=transform.position.x+",";
txt=txt+transform.position.y+",";
txt=txt+transform.position.z;
swreg2.WriteLine(txt);
swreg2.Flush();
swreg2.Close();}
}
I have the code that saves my customization data to a file, but thanks for the reconfir$$anonymous$$g that this is the best way to go about it and for the code snippet.