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. Dismiss Notice

Object position and rotation saving

Discussion in 'Scripting' started by concretegames, Mar 1, 2022.

  1. concretegames

    concretegames

    Joined:
    Dec 2, 2016
    Posts:
    15
    Hey guys, can somebody help me with this script ? I am pretty new in C#, and i looked at it all night but could not find the mistake. I want to make a script that will save the position of an object using Serialize, and when loading the game, the saved objects's positon and rotation will be transferred to it without destryoing the object and making a new instance of it. I will do the calls trough other scripts, for now i ve done them trough keys. Thank you! Ive tryied to do it in two scripts, one attached to the gameManager, and one to every object that i need to save. P.S. Don't kill me for the beginer style of coding. Thanks!

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. [System.Serializable]
    5. public class SalvableObject : MonoBehaviour
    6. {
    7.     public string ObjectName;
    8.     public Vector3 ObjectPosition;
    9.     public Quaternion ObjectRotation;
    10.     public List<SalvableObject> salvableObject = new List<SalvableObject>();
    11.     public float ObjectPosX, ObjectPosY, ObjectPosZ;
    12.     public float ObjectRotX, ObjectRotY, ObjectRotZ, ObjectRotW;
    13.     public KeyCode SavePosKey = KeyCode.Alpha1;
    14.     public KeyCode LoadPosKey = KeyCode.Alpha2;
    15.     public KeyCode ClearPosKey = KeyCode.Alpha3;
    16.     SaveLoadData saveLoadData;
    17.     private void Update()
    18.     {
    19.                 if (Input.GetKeyDown(SavePosKey))
    20.         {
    21.             GetObjectPosRot();
    22.             saveLoadData.SavePOS();
    23.         }
    24.                 if (Input.GetKeyDown(LoadPosKey))
    25.         {
    26.             saveLoadData.LoadPos();
    27.             SetObjectPosition();
    28.         }
    29.                 if (Input.GetKeyDown(ClearPosKey))
    30.         {
    31.             saveLoadData.ClearSave();
    32.         }
    33.     }
    34.     public void GetObjectPosRot()
    35.     {
    36.         ObjectName = gameObject.name;
    37.         ObjectPosition = gameObject.transform.position;
    38.         ObjectPosX = ObjectPosition.x;
    39.         ObjectPosY = ObjectPosition.y;
    40.         ObjectPosZ = ObjectPosition.z;
    41.         ObjectRotation = gameObject.transform.rotation;
    42.         ObjectRotX = ObjectRotation.x;
    43.         ObjectRotY = ObjectRotation.y;
    44.         ObjectRotZ = ObjectRotation.z;
    45.         ObjectRotW = ObjectRotation.w;
    46.         Debug.Log("Position and rotation Saved" + "Pos:" + ObjectPosition + "Rot:" + ObjectRotation);
    47.     }
    48.     public void  SetObjectPosition()
    49.     {
    50. /*       Vector3 NewObjectPos =  new Vector3(ObjectPosX, ObjectPosY, ObjectPosZ);
    51.         gameObject.transform.position = NewObjectPos;
    52.         Quaternion NewObjectRot = new Quaternion(ObjectRotX, ObjectRotY, ObjectRotZ, ObjectRotW);
    53.         gameObject.transform.rotation = NewObjectRot;*/
    54.         for (int i = 0; i < salvableObject.Count; i++)
    55.         {
    56.             GameObject obj = gameObject;
    57.             obj.transform.position = salvableObject[i].ObjectPosition;
    58.             obj.transform.rotation = salvableObject[i].ObjectRotation;
    59.         }
    60.     }
    and the second one

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System.IO;
    5. using System.Runtime.Serialization.Formatters.Binary;
    6. using UnityEngine.SceneManagement;
    7. [System.Serializable]
    8. public class SaveLoadData : MonoBehaviour
    9. {
    10.     public List<SalvableObject> salvableObject;
    11.     public bool AutoLoadSave = true;
    12.     const string OBJ_SUB = "/objects";
    13.     public string path;
    14.     SalvableObject SaveOBJ;
    15.     void Start()
    16.     {
    17.        path = Application.persistentDataPath + OBJ_SUB + SceneManager.GetActiveScene().buildIndex;
    18.     }
    19.     public void SavePOS()
    20.     {
    21.         salvableObject = SaveOBJ.salvableObject;
    22.         FileStream fs = File.Create(path);
    23.         BinaryFormatter bf = new BinaryFormatter();
    24.         bf.Serialize(fs, salvableObject);
    25.         fs.Close();
    26.     }
    27.     public void LoadPos()
    28.     {
    29.         FileStream fs = File.Open(path, FileMode.Open);
    30.         BinaryFormatter bf = new BinaryFormatter();
    31.         if (fs.Length > 0)
    32.         {
    33.             salvableObject = (List<SalvableObject>)bf.Deserialize(fs);
    34.             salvableObject = SaveOBJ.salvableObject;
    35.         }
    36.     }
    37.     public void ClearSave()
    38.     {
    39.         BinaryFormatter bf = new BinaryFormatter();
    40.         File.Delete(path);
    41.         Debug.Log("deleted...");
    42.     }
    43. }
    44. }
    Thank you!
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,894
    I want to know if there's an old forum post or youtube tutorial telling people to use binary formatter. Why is everyone posting with a save game issue using it?

    The long and short is don't use it. It's old, it's unsafe, and Microsoft themselves tell you not to use it.

    Just use regular JSON if you're learning. Either with the built in JSON utility (be careful of its short falls, of which there are many), or something more robust like Newtonsoft.JSON.

    What mistake? You haven't told us what's not working so we can't exactly help you.
     
    PraetorBlue likes this.
  3. concretegames

    concretegames

    Joined:
    Dec 2, 2016
    Posts:
    15
    Well, it is not working - when i play the game, i save using Alpha.1, then manually move the cube i have asgined the script to it, and when i load using Alpha.2, the cube does not get to the initial (Saved) position. (In my game project, i have built a system to move pick it up, drop, etc, but i started a new project in order to learn how to make a save/load system.)
     
  4. concretegames

    concretegames

    Joined:
    Dec 2, 2016
    Posts:
    15
    okay, i managed to understand a bit how Json is working, and i made a script (composed from two scripts actually) wich is working now. But i wonder how hard would it be to modify it in order to save multiple's objects positions. Can somebody help ? Thank you!
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System.IO;
    5.  
    6. public class GameHandler : MonoBehaviour
    7. {
    8.     PlayerData playerData = new PlayerData();
    9.     public MoveObject moveObject;
    10.     private string path;
    11.  
    12.  
    13.  
    14.     public KeyCode SaveObjPosKey = KeyCode.Alpha1;
    15.     public KeyCode LoadObjPosKey = KeyCode.Alpha2;
    16.     public KeyCode DeleteObjPosKey = KeyCode.Alpha3;
    17.  
    18.  
    19.  
    20.  
    21.  
    22.     void Start()
    23.     {
    24.  
    25.         path = Application.dataPath + "/saveFile.json";
    26.         Debug.Log("SaveManager is running");
    27.  
    28.     }
    29.  
    30.     void Update()
    31.     {
    32.         if (Input.GetKeyDown(SaveObjPosKey))
    33.         {
    34.             SaveObjectPosition();
    35.         }
    36.         if (Input.GetKeyDown(LoadObjPosKey))
    37.         {
    38.             LoadObjectPosition();
    39.         }
    40.         if (Input.GetKeyDown(DeleteObjPosKey))
    41.         {
    42.             DeleteObjectPosition();
    43.         }
    44.     }
    45.     void SaveObjectPosition()
    46.     {
    47.         playerData.position = moveObject.gameObject.transform.position;
    48.         playerData.rotation = moveObject.transform.rotation;
    49.         playerData.objectName = moveObject.ObjName;
    50.         string json = JsonUtility.ToJson(playerData);
    51.         File.WriteAllText(path, json);
    52.         Debug.Log("Saved!" + path);
    53.     }
    54.     void LoadObjectPosition()
    55.     {
    56.         if (File.Exists(path))
    57.         {
    58.             string json = File.ReadAllText(path);
    59.             PlayerData loadedPlayerData = JsonUtility.FromJson<PlayerData>(json);
    60.             Debug.Log("Loaded!" + path);
    61.             moveObject.transform.position = loadedPlayerData.position;
    62.             moveObject.transform.rotation = loadedPlayerData.rotation;
    63.         }
    64.  
    65.         else
    66.         {
    67.             Debug.Log("SaveFile does not exists! Aborting load!");
    68.         }
    69.     }
    70.     void DeleteObjectPosition()
    71.     {
    72.         if (File.Exists(path))
    73.         {
    74.             File.Delete(path);
    75.             Debug.Log("Deleted!");
    76.         }
    77.         else
    78.         {
    79.             Debug.Log("Delete What?!");
    80.         }
    81.     }
    82.  
    83.     private class PlayerData
    84.     {
    85.  
    86.         public Vector3 position;
    87.         public Quaternion rotation;
    88.         public string objectName;
    89.  
    90.     }
    91. }
    92.  

    and the movement script, just to make it easier to test:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class MoveObject : MonoBehaviour
    6. {
    7.     public float moveSpeed = 0.3f;
    8.     public Vector3 ObjPosition;
    9.     public Quaternion ObjRotation;
    10.     public string ObjName;
    11.     void Start()
    12.     {
    13.         ObjName = gameObject.name;
    14.     }
    15.  
    16.     void Update()
    17.     {
    18.  
    19.         float Horizontal = Input.GetAxis("Horizontal");
    20.         float Vertical = Input.GetAxis("Vertical");
    21.  
    22.         if (Input.GetAxis("Horizontal") != 0 || Input.GetAxis("Vertical") != 0)
    23.         {
    24.             gameObject.transform.position += new Vector3(-Horizontal * moveSpeed, Vertical * moveSpeed, 0);
    25.         }
    26.  
    27.  
    28.     }
    29. }
    30.  
     
  5. concretegames

    concretegames

    Joined:
    Dec 2, 2016
    Posts:
    15
    tryied something like this but it is saving only one's object position, even if there are multiple objects in the MoveObject[] array.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System.IO;
    5.  
    6. public class GameHandler : MonoBehaviour
    7. {
    8.     PlayerData playerData = new PlayerData();
    9.     public MoveObject[] moveObject;
    10.     private string path;
    11.  
    12.  
    13.  
    14.     public KeyCode SaveObjPosKey = KeyCode.Alpha1;
    15.     public KeyCode LoadObjPosKey = KeyCode.Alpha2;
    16.     public KeyCode DeleteObjPosKey = KeyCode.Alpha3;
    17.  
    18.  
    19.  
    20.  
    21.  
    22.     void Start()
    23.     {
    24.  
    25.         path = Application.dataPath + "/saveFile.json";
    26.         Debug.Log("SaveManager is running");
    27.  
    28.     }
    29.  
    30.     void Update()
    31.     {
    32.         if (Input.GetKeyDown(SaveObjPosKey))
    33.         {
    34.             SaveObjectPosition();
    35.         }
    36.         if (Input.GetKeyDown(LoadObjPosKey))
    37.         {
    38.             LoadObjectPosition();
    39.         }
    40.         if (Input.GetKeyDown(DeleteObjPosKey))
    41.         {
    42.             DeleteObjectPosition();
    43.         }
    44.     }
    45.     void SaveObjectPosition()
    46.     {
    47.  
    48.         for (int i = 0; i < moveObject.Length; i++)
    49.         {
    50.             playerData.position  = moveObject[i].gameObject.transform.position;
    51.             playerData.rotation = moveObject[i].transform.rotation;
    52.             playerData.objectName = moveObject[i].ObjName;
    53.  
    54.         }
    55.  
    56.         string json = JsonUtility.ToJson(playerData);
    57.         File.WriteAllText(path, json);
    58.         Debug.Log("Saved!" + path);
    59.     }
    60.     void LoadObjectPosition()
    61.     {
    62.         if (File.Exists(path))
    63.         {
    64.             string json = File.ReadAllText(path);
    65.             PlayerData loadedPlayerData = JsonUtility.FromJson<PlayerData>(json);
    66.             Debug.Log("Loaded!" + path);
    67.             for (int i = 0; i < moveObject.Length; i++)
    68.             {
    69.                 moveObject[i].transform.position = loadedPlayerData.position;
    70.  
    71.             }
    72.        }
    73.  
    74.         else
    75.         {
    76.             Debug.Log("SaveFile does not exists! Aborting load!");
    77.         }
    78.     }
    79.     void DeleteObjectPosition()
    80.     {
    81.         if (File.Exists(path))
    82.         {
    83.             File.Delete(path);
    84.             Debug.Log("Deleted!");
    85.         }
    86.         else
    87.         {
    88.             Debug.Log("Delete What?!");
    89.         }
    90.     }
    91.  
    92.     private class PlayerData
    93.     {
    94.  
    95.         public Vector3 position;
    96.         public Quaternion rotation;
    97.         public string objectName;
    98.  
    99.     }
    100. }
    101.