Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Save Game

Discussion in 'Scripting' started by UnityUser9860, Jun 18, 2016.

  1. UnityUser9860

    UnityUser9860

    Joined:
    Dec 8, 2015
    Posts:
    179
    Hello!

    Ive made a functional multiplayer sandbox and I'm trying to add a function to save the world how would I go about doing this?

    P.S I know how to network it I just need to know how to actually SAVE the game data like player buildings / creations
     
  2. Severos

    Severos

    Joined:
    Oct 2, 2015
    Posts:
    181
    One way of doing it is saving these objects into a DB, and when you start the game load them from there. this shouldn't be hard, but requires external stuff.
    Another way (I'm not sure or familiar with it) is using Scriptable objects, you're on your own in this as I have no idea about it, just happen to read it somewhere.
     
  3. jaasso

    jaasso

    Joined:
    Jun 19, 2013
    Posts:
    64
    heres a few example scripts that save and load a few variables like position and an array of strings to a file using json, not entirely sure if they follow the best practices but they work and are simple enough for me. you can also find a lot of info about saving using json for example here http://docs.unity3d.com/Manual/JSONSerialization.html

    (this doesnt need to be attached to a gameobject)
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. [System.Serializable]
    5. public class SaveLoadData
    6. {
    7.     public bool dead;
    8.  
    9.     public float posX,posY,posZ,rotY;
    10.  
    11.     public string[] itemList;
    12. }
    (attach to object to move it around)
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class PlayerControllerExample : MonoBehaviour
    5. {
    6.     public bool dead=false;
    7.  
    8.     public string[] itemList=new string[0];
    9.  
    10.     void Update()
    11.     {
    12.         transform.RotateAround(transform.position,Vector3.up,Input.GetAxis("Mouse X"));
    13.         transform.Translate(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical"));
    14.     }
    15. }
    (attach to any gameobject. it's currently using this gameobject's name for loading and saving and theres probably other stuff that should be changed but it's an example)

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.IO;
    4. using System;
    5. using System.Security.Cryptography;
    6. using System.Text;
    7.  
    8. public class SaveLoadManager : MonoBehaviour
    9. {
    10.     SaveLoadData savedJson;
    11.     PlayerControllerExample controller;
    12.     string json;
    13.     public bool useDecrypt;
    14.  
    15.     void Awake()
    16.     {
    17.         DontDestroyOnLoad(gameObject);
    18.  
    19.         savedJson=new SaveLoadData();
    20.         controller=FindObjectOfType<PlayerControllerExample>();
    21.     }
    22.  
    23.     void OnGUI()
    24.     {
    25.         if(GUILayout.Button("save"))
    26.         {
    27.             Save(gameObject.name);
    28.         }
    29.         if(GUILayout.Button("load"))
    30.         {
    31.             Load(gameObject.name);
    32.         }
    33.     }
    34.  
    35.     public void Save(string _name)
    36.     {
    37.         savedJson.posX=controller.transform.position.x;
    38.         savedJson.posY=controller.transform.position.y;
    39.         savedJson.posZ=controller.transform.position.z;
    40.  
    41.         savedJson.rotY=controller.transform.eulerAngles.y;
    42.  
    43.         savedJson.dead=controller.dead;
    44.  
    45.         savedJson.itemList=controller.itemList;
    46.  
    47.         json = JsonUtility.ToJson(savedJson);
    48.  
    49.         if(useDecrypt)
    50.         {
    51.             json= Encrypt(json);
    52.         }
    53.  
    54.         using(StreamWriter writer = new StreamWriter(Application.persistentDataPath + _name + ".txt", false))
    55.         {
    56.             writer.Write(json);
    57.         }
    58.     }
    59.     public void Load(string _name)
    60.     {
    61.         string fileName = Application.persistentDataPath + _name + ".txt";
    62.  
    63.         if(File.Exists (fileName))
    64.         {
    65.             using(StreamReader reader = new StreamReader(fileName))
    66.             {
    67.                 string s = reader.ReadToEnd();
    68.  
    69.                 if(useDecrypt)
    70.                 {
    71.                     s=Decrypt(s);
    72.                 }
    73.                 savedJson=JsonUtility.FromJson<SaveLoadData>(s);
    74.             }
    75.         }
    76.  
    77.         controller.dead=savedJson.dead;
    78.         controller.transform.position=new Vector3(savedJson.posX,savedJson.posY,savedJson.posZ);
    79.         controller.transform.eulerAngles=new Vector3(0,savedJson.rotY,0);
    80.         controller.itemList=savedJson.itemList;
    81.     }
    82.  
    83.     public static string Decrypt(string cipherText)
    84.     {
    85.         string EncryptionKey = "abc123";
    86.         cipherText = cipherText.Replace(" ", "+");
    87.         byte[] cipherBytes = Convert.FromBase64String(cipherText);
    88.         using (Aes encryptor = Aes.Create())
    89.         {
    90.             Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
    91.             encryptor.Key = pdb.GetBytes(32);
    92.             encryptor.IV = pdb.GetBytes(16);
    93.             using (MemoryStream ms = new MemoryStream())
    94.             {
    95.                 using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
    96.                 {
    97.                     cs.Write(cipherBytes, 0, cipherBytes.Length);
    98.                     cs.Close();
    99.                 }
    100.                 cipherText = Encoding.Unicode.GetString(ms.ToArray());
    101.             }
    102.         }
    103.         return cipherText;
    104.     }
    105.  
    106.     public static string Encrypt(string clearText)
    107.     {
    108.         string EncryptionKey = "abc123";
    109.         byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
    110.         using (Aes encryptor = Aes.Create())
    111.         {
    112.             Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
    113.             encryptor.Key = pdb.GetBytes(32);
    114.             encryptor.IV = pdb.GetBytes(16);
    115.             using (MemoryStream ms = new MemoryStream())
    116.             {
    117.                 using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
    118.                 {
    119.                     cs.Write(clearBytes, 0, clearBytes.Length);
    120.                     cs.Close();
    121.                 }
    122.                 clearText = Convert.ToBase64String(ms.ToArray());
    123.             }
    124.         }
    125.         return clearText;
    126.     }
    127. }
     
  4. Severos

    Severos

    Joined:
    Oct 2, 2015
    Posts:
    181
    The above serialization isn't really the best practice, actually you don't really need another class to save data, just mark the fields as serializable and use NewtonSoft to serialize it to json, another thing would be normal binary serialization.
    Just make sure to know what data you should save and what doesn't need to be saved.
     
    jaasso likes this.
  5. UnityUser9860

    UnityUser9860

    Joined:
    Dec 8, 2015
    Posts:
    179
    ok thanks guys your a great help ill do some stuff now