- Home /
Saving GameObject to file
Hello, I'm new in topics like saving game progress and I have a question. What I need is to save whole GameObject to file on button click (when game is closing) and later when turning game again on I want to Instantiate that GameObject from saved file. Is there any way to do that? What i tried now is:
Doing class with GameObject:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class SaveLevel
{
public GameObject Object;
public SaveLevel(GameObject object)
{
Object = object;
}
}
And voids for buttons to save and load it:
public void SaveLevelOnButton()
{
SaveLevel save = new SaveLevel(/*GameObject i want to save. Let's say:*/ ObjectToSave);
string json = JsonUtility.ToJson(save);
File.WriteAllText(Application.persistentDataPath + "/LevelState.json", json);
}
public void LoadLevelOnButton()
{
GameObject LoadedLevel;
string json = File.ReadAllText(Application.persistentDataPath + "/LevelState.json");
LoadedLevel = JsonUtility.FromJson<SaveLevel>(json).gameObject;
Instantiate(LoadedLevel, new Vector3(0, 0, 0), Quaternion.identity);
}
That code is creating the GameObject "ObjectToSave" from begin like it wasn't saved.
Answer by xbassad · Apr 17, 2019 at 05:59 PM
If you want to save your game progress just use PlayerPrefs.Save()
$$anonymous$$y GameObject to save has more GameObjects in it as childerns and every of this children has a lot of data. That's why I wanted just to save the GameObject. Do you think when i turn game off and on, will i get the data like they were on quiting the game? CanPlayerPrefs do that?
Check the documentation https://docs.unity3d.com/ScriptReference/PlayerPrefs.html
and also check this video
So, PlayerPrefs is a good way to save the data. I know now that i can't save whole GameObject. I'm going to change my scripts so I can save the variables. Thanks for your time!
Answer by NikitaDemidov · Apr 17, 2019 at 07:52 PM
I wouldn't save GameObject. I would save some Attributes. Example: A normal 3D cube: "P-x=" + obj.transform.position.x + "P-y" + obj.transform.position.x ... You can put all that in a txt-File with System.IO;
Hello, Yeah, thanks, I know now that i can't save whole GameObject. I'm going to change my scripts so i can save the attributes/variables by the method with PlayerPref. Thank you for your time!
Your answer
Follow this Question
Related Questions
Hard question about saving and loading 1 Answer
Problem whith save system,Problem whith save code 0 Answers
Can gameobject be exported as unity3d form? 0 Answers
How to save and load any data type? 1 Answer
Save Multiple GameObject with XML 1 Answer