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

[Solved] How Do I Save And Load Worlds In Unity 5

Discussion in 'Scripting' started by Benj4_, Sep 27, 2016.

  1. Benj4_

    Benj4_

    Joined:
    Nov 12, 2015
    Posts:
    38
    Hello All! I Am Wondering How Do I Save And Load Worlds In Unity, So Basically I Am Creating A Procedural Generation Project, And Would Like Users To Save And Load Worlds That They Create In The Game :)
    And I Want To Make A Folder In The Game Directory And Name It Saves And Save The Files In There

    I Have Looked For Tutorials Everywhere
     
  2. DroidifyDevs

    DroidifyDevs

    Joined:
    Jun 24, 2015
    Posts:
    1,724
    Hi!

    First of all, you don't need to capitalize every single word :p

    This really depends on how you're procedurally generating your world. I have no idea how you're doing it, but right off the bat: Unity does not have a feature to save world state. While I think it would be insanely useful, currently you'll have to think of other methods.

    Can you be more specific on how you're generating your world?
     
  3. Benj4_

    Benj4_

    Joined:
    Nov 12, 2015
    Posts:
    38
    2 Things
    1.
    It's A Habit I Am Really Trying To Stop << As You Can See I Kinda can't it start When I Begin Coding All The Time
    2.
    Oh, That's A Shame :( Heres My Code For Generating Its Quite Simple But I Am Planing To Rewrite The Code Later To Include Chunks, So It Dues Not Lag, Trying To Generate 5000000 Blocks+ For An Infinite World :p

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Block {
    5.     public int type;
    6.     public bool vis;
    7.     public GameObject block;
    8.  
    9.     public Block(int t, bool v, GameObject b) {
    10.  
    11.         type = t;
    12.         vis = v;
    13.         block = b;
    14.     }
    15. }
    16.  
    17. public class GeneratorRebuilt : MonoBehaviour {
    18.  
    19.     public static int width = 64;
    20.     public static int depth = 64;
    21.     public static int height = 200;
    22.     public int heightScale = 20;
    23.     public int heightOffset = 100;
    24.     public float detailScale = 25.0f;
    25.     public int sandPlacement = 110;
    26.     public int grassPlacement = 117;
    27.     public int dirtPlacement = 114;
    28.     public int stonePlacement = 0;
    29.     public string GeneratorVersion;
    30.  
    31.  
    32.    
    33.     public GameObject grassBlock;
    34.     public GameObject dirtBlock;
    35.     public GameObject stoneBlock;
    36.     public GameObject sandBlock;
    37.     public GameObject cloudBlock;
    38.     public GameObject DiamondOreBlock;
    39.     public GameObject BedrockBlock;
    40.     public GameObject FirstPersonCamera;
    41.     public GameObject ThridPersonCamera;
    42.  
    43.     Block[,,] worldBlocks = new Block[width,height,depth];
    44.  
    45.  
    46.     // Use this for initialization
    47.     void Start () {
    48.         Debug.Log ("Loading Generator");
    49.         if (GeneratorVersion == "") {
    50.             Debug.LogError ("[Generator Rebuilt] Failed To Get Version... Please Input The Version Number In Your Gamemanager");
    51.             Debug.LogError ("[Generator Rebuilt] GameObject And Place In The Version In The Generator Version");
    52.         } else {
    53.             Debug.LogWarning ("[Generator Rebuilt] Generator Loaded Currectly");
    54.             Debug.Log ("[Generator Rebuilt] Generator Version: " + GeneratorVersion);
    55.             Debug.LogWarning ("[Generator Rebuilt] Building Terrain");
    56.             Debug.Log ("[Generator Rebuilt] Spawning Player");
    57.             Generate ();
    58.         }
    59.     }
    60.     void Generate() {
    61.         int seed = (int)Network.time * 10;
    62.         for(int z = 0; z < depth; z++) {
    63.             //Setting Custom Seed
    64.             for(int x = 0; x < width; x++) {
    65.                 int y = (int) (Mathf.PerlinNoise((x+seed)/detailScale, (z+seed)/detailScale) * heightScale) + heightOffset;
    66.                 Vector3 blockPos = new Vector3(x,y,z);
    67.                 CreateBlock (y, blockPos, true);
    68.                 while(y > 0) {
    69.                     y--;
    70.                     blockPos = new Vector3 (x,y,z);
    71.                     CreateBlock (y, blockPos, false);
    72.             }
    73.         }
    74.     }
    75.         DrawClouds (3, 50);
    76.         DigMines (2, 500);
    77.         Debug.Log ("The Current Level Seed: "  + seed);
    78. }
    79.  
    80.     void DrawClouds(int numClouds, int cSize) {
    81.         for(int i = 0; i < numClouds; i++) {
    82.             int xpos = Random.Range(0, width);
    83.             int zpos = Random.Range (0, depth);
    84.  
    85.             for (int j = 0; j < cSize; j++) {
    86.                 Vector3 blockPos = new Vector3 (xpos, height - 1, zpos);
    87.                 GameObject newBlock = (GameObject) Instantiate (cloudBlock, blockPos, Quaternion.identity);
    88.                 worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z] = new Block (5, true, newBlock);
    89.                 xpos += Random.Range (-1, 2);
    90.                 zpos += Random.Range (-1, 2);
    91.                 if (xpos < 0 || xpos >= width) xpos = width / 2;
    92.                 if (zpos < 0 || zpos >= depth)zpos = depth / 2;
    93.             }
    94.         }
    95.     }
    96.  
    97.     void DigMines(int numMines, int mSize) {
    98.            
    99.         int holeSize = 2;
    100.         for (int i = 0; i < numMines; i++) {
    101.             int xpos = Random.Range(10, width-10);
    102.             int ypos = Random.Range(10, height-10);
    103.             int zpos = Random.Range (10, depth-10);
    104.             for (int j = 0; j < mSize; j++) {
    105.                     for (int x = -holeSize; x <= holeSize; x++)
    106.                    
    107.                         for(int y = -holeSize; y <= holeSize; y++)
    108.                        
    109.                             for(int z = -holeSize; z <= holeSize; z++) {
    110.                            
    111.                                 if(!(x == 0 && y == 0 && z == 0)) {
    112.                                     Vector3 blockPos = new Vector3(xpos+x, ypos+y, zpos+z);
    113.                                     if(worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z] != null)
    114.                                         Destroy(worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z].block);
    115.                                 worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z] = null;
    116.                     }
    117.                 }
    118.  
    119.                 xpos += Random.Range (-1, 2);
    120.                 ypos += Random.Range (-1, 2);
    121.                 zpos += Random.Range (-1, 2);
    122.                 if (xpos < holeSize || xpos >= width - holeSize) xpos = width / 2;
    123.                 if (ypos < holeSize || ypos >= height - holeSize) ypos = height / 2;
    124.                 if (zpos < holeSize || zpos >= depth - holeSize) zpos = depth / 2;
    125.             }
    126.         }
    127.         for(int z = 1; z < depth-1; z++) {
    128.             for (int x = 1; x < width-1; x++) {
    129.                 for (int y = 1; y < height-1; y++) {
    130.                     if (worldBlocks [x, y, z] == null) {
    131.                         for (int x1 = -1; x1 <= 1; x1++)
    132.                             for (int y1 = -1; y1 <= 1; y1++)
    133.                                 for (int z1 = -1; z1 <= 1; z1++) {
    134.  
    135.                                     if (!(x1 == 0 && y1 == 0 && z1 == 0)) {
    136.                                         Vector3 neighbour = new Vector3 (x+x1, y+y1, z+z1);
    137.                                         DrawBlock (neighbour);
    138.                             }
    139.                         }
    140.                     }
    141.                 }
    142.             }
    143.         }
    144.     }
    145.  
    146.         void CreateBlock(int y, Vector3 blockPos, bool create) {
    147.  
    148.         GameObject newBlock = null;
    149.         if (y > grassPlacement) {
    150.             if(create)
    151.                 newBlock = (GameObject) Instantiate (grassBlock, blockPos, Quaternion.identity);
    152.             worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z] = new Block (1, create, newBlock);
    153.         } else if (y > dirtPlacement) {
    154.                     if(create)
    155.                             newBlock = (GameObject) Instantiate (dirtBlock, blockPos, Quaternion.identity);
    156.             worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z] = new Block (2, create, newBlock);
    157.             } else if (y > sandPlacement) {
    158.                         if(create)
    159.                             newBlock = (GameObject) Instantiate (sandBlock, blockPos, Quaternion.identity);
    160.             worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z] = new Block (3, create, newBlock);
    161.                 } else
    162.                     if (y > stonePlacement) {
    163.                             if(create)
    164.                                 newBlock = (GameObject)    Instantiate (stoneBlock, blockPos, Quaternion.identity);
    165.                 worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z] = new Block (4, create, newBlock);
    166.             } else if(y > 70 && y < 80 && Random.Range(0,100) < 10) {
    167.                 if(create)
    168.                     newBlock = (GameObject)    Instantiate (DiamondOreBlock, blockPos, Quaternion.identity);
    169.                 worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z] = new Block (5, create, newBlock);
    170.             } else if(y > 1 && y < 5 && Random.Range(0,100) < 60) {
    171.                 if(create)
    172.                     newBlock = (GameObject)    Instantiate (BedrockBlock, blockPos, Quaternion.identity);
    173.                 worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z] = new Block (6, create, newBlock);
    174.         }
    175.     }
    176.  
    177.     void DrawBlock(Vector3 blockPos) {
    178.  
    179.         if (worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z] == null) return;
    180.  
    181.         if (!worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z].vis) {
    182.             GameObject newBlock = null;
    183.             worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z].vis = true;
    184.  
    185.             if (worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z].type == 1) {
    186.                 newBlock = (GameObject)Instantiate (grassBlock, blockPos, Quaternion.identity);
    187.             } else if (worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z].type == 2) {
    188.                 newBlock = (GameObject)Instantiate (dirtBlock, blockPos, Quaternion.identity);
    189.             } else if (worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z].type == 3) {
    190.                 newBlock = (GameObject)Instantiate (sandBlock, blockPos, Quaternion.identity);
    191.             } else if (worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z].type == 4) {
    192.                 newBlock = (GameObject)Instantiate (stoneBlock, blockPos, Quaternion.identity);
    193.         } else if (worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z].type == 5) {
    194.                 newBlock = (GameObject)Instantiate (DiamondOreBlock, blockPos, Quaternion.identity);
    195.             } else if (worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z].type == 6) {
    196.  
    197.                 newBlock = (GameObject)Instantiate (BedrockBlock, blockPos, Quaternion.identity);
    198.             } else {
    199.                 worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z].vis = false;
    200.             }
    201.         }
    202.     }
    203.        
    204.    
    205.     // Update is called once per frame
    206.     void Update() {
    207.         if (Input.GetMouseButtonDown (0)) {
    208.             RaycastHit hit;
    209.             Ray ray = Camera.main.ScreenPointToRay (new Vector3 (Screen.width / 2.0f, Screen.height / 2.0f, 0));
    210.             if (Physics.Raycast (ray, out hit, 3.0f)) {
    211.                 Vector3 blockPos = hit.transform.position;
    212.  
    213.                 if ((int)blockPos.y == 0)
    214.                     return;
    215.  
    216.                 worldBlocks [(int)blockPos.x, (int)blockPos.y, (int)blockPos.z] = null;
    217.  
    218.                 Destroy (hit.transform.gameObject);
    219.  
    220.                 for (int x = -1; x <= 1; x++)
    221.                     for (int y = -1; y <= 1; y++)
    222.                         for (int z = -1; z <= 1; z++) {
    223.  
    224.                             if (!(x == 0 && y == 0 && z == 0)) {
    225.                                 Vector3 neighbour = new Vector3 (blockPos.x + x, blockPos.y + y, blockPos.z + z);
    226.                                 DrawBlock (neighbour);
    227.                             }
    228.                         }
    229.             }
    230.         } else if (Input.GetMouseButtonDown (1)) {
    231.             RaycastHit hit;
    232.             Ray ray = Camera.main.ScreenPointToRay (new Vector3 (Screen.width / 2.0f, Screen.height / 2.0f, 0));
    233.             if (Physics.Raycast (ray, out hit, 3.0f)) {
    234.                 Vector3 blockPos = hit.transform.position;
    235.                 Vector3 hitVector = blockPos - hit.point;
    236.  
    237.                 hitVector.x = Mathf.Abs (hitVector.x);
    238.                 hitVector.y = Mathf.Abs (hitVector.y);
    239.                 hitVector.z = Mathf.Abs (hitVector.z);
    240.  
    241.                 if (hitVector.x > hitVector.z && hitVector.x > hitVector.y)
    242.                     blockPos.x -= (int)Mathf.RoundToInt (ray.direction.x);
    243.                 else if(hitVector.y > hitVector.x && hitVector.y > hitVector.z)
    244.                     blockPos.y -= (int)Mathf.RoundToInt (ray.direction.y);
    245.                 else
    246.                     blockPos.z -= (int)Mathf.RoundToInt (ray.direction.z);
    247.  
    248.                 CreateBlock ((int)blockPos.y, blockPos, true);
    249.  
    250.             }
    251.         }
    252.     }
    253. }
    254.  
    Feel Free To Use This Code Because It Is From A Tutorial (Almost All 300 Lines:rolleyes:)
     
  4. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    you might find this series interesting, especially the most recent vid

     
    DroidifyDevs likes this.
  5. Benj4_

    Benj4_

    Joined:
    Nov 12, 2015
    Posts:
    38
    This Is Not Really What I Am Looking For... I Am Looking For Something To Save And Load With Blocks, Kinda Like Minecraft Blocks
     
  6. Benj4_

    Benj4_

    Joined:
    Nov 12, 2015
    Posts:
    38
  7. Benj4_

    Benj4_

    Joined:
    Nov 12, 2015
    Posts:
    38
    Bump(Again) I NEED HELP
     
  8. DroidifyDevs

    DroidifyDevs

    Joined:
    Jun 24, 2015
    Posts:
    1,724
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.IO;
    4. using System.Runtime.Serialization.Formatters.Binary;
    5. using System.Runtime.Serialization;
    6. using System;
    7. using System.Collections.Generic;
    8.  
    9. //this is SaveInfoNewer.cs
    10. //this script saves and loads all the info we want
    11. public class SaveInfoNewer : MonoBehaviour
    12. {
    13.     public SlotLoader SlotLoader;
    14.     //data is what is finally saved
    15.     public Dictionary<string, int> data;
    16.  
    17.     void Awake()
    18.     {
    19.         //LoadUpgradeData();
    20.         LoadData();
    21.         //WARNING! data.Clear() deletes EVERYTHING
    22.         //data.Clear();
    23.         //SaveData();
    24.     }
    25.  
    26.     public void LoadData()
    27.     {
    28.         //this loads the data
    29.         data = SaveInfoNewer.DeserializeData<Dictionary<string, int>>("PleaseWork.save");
    30.     }
    31.  
    32.     public void SaveData()
    33.     {
    34.         //this saves the data
    35.         SaveInfoNewer.SerializeData(data, "PleaseWork.save");
    36.     }
    37.     public static void SerializeData<T>(T data, string path)
    38.     {
    39.         //this is just magic to save data.
    40.         //if you're interested read up on serialization
    41.         FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
    42.         BinaryFormatter formatter = new BinaryFormatter();
    43.         try
    44.         {
    45.             formatter.Serialize(fs, data);
    46.             Debug.Log("Data written to " + path + " @ " + DateTime.Now.ToShortTimeString());
    47.         }
    48.         catch (SerializationException e)
    49.         {
    50.             Debug.LogError(e.Message);
    51.         }
    52.         finally
    53.         {
    54.             fs.Close();
    55.         }
    56.     }
    57.  
    58.     void CheckScores()
    59.     {
    60.         if (Player1Score > Player2Score)
    61.         {
    62.             //Win code
    63.             PlayerPrefs.SetInt("Player1Score", Player1Score);
    64.         }
    65.  
    66.         else
    67.         {
    68.             //player 2 wins
    69.             //do same for player 2
    70.         }
    71.     }
    72.  
    73.     public static T DeserializeData<T>(string path)
    74.     {
    75.         //this is the magic that deserializes the data so we can load it
    76.         T data = default(T);
    77.  
    78.         if (File.Exists(path))
    79.         {
    80.             FileStream fs = new FileStream(path, FileMode.Open);
    81.             try
    82.             {
    83.                 BinaryFormatter formatter = new BinaryFormatter();
    84.                 data = (T)formatter.Deserialize(fs);
    85.                 Debug.Log("Data read from " + path);
    86.             }
    87.             catch (SerializationException e)
    88.             {
    89.                 Debug.LogError(e.Message);
    90.             }
    91.             finally
    92.             {
    93.                 fs.Close();
    94.             }
    95.         }
    96.         return data;
    97.     }
    98. }
    99.  
    Also, screaming BUMP at 6AM and then 7:50AM isn't a good way to get answers...
     
  9. Benj4_

    Benj4_

    Joined:
    Nov 12, 2015
    Posts:
    38
    I'm In Austraila And I Been Waiting For A Reply All Freaking Day
     
  10. Benj4_

    Benj4_

    Joined:
    Nov 12, 2015
    Posts:
    38
    Please Write A Tutorial About This Please
     
  11. DroidifyDevs

    DroidifyDevs

    Joined:
    Jun 24, 2015
    Posts:
    1,724
    No one is going to make a tutorial for you. You have to learn how to think independently. I gave you a script that loads and saves data permanently. I could hold your hand and show you line-by-line how to save and load the cube positions, but that's not learning.

    Here's some hints:

    Code (CSharp):
    1.  
    2. public Dictionary<string, Vector3> data;
    So if you modify my script's dictionary to that, you'll be able to save a string and Vector3. In the string, you'll put your block's name, and in the Vector3 you'll save its position. Note that every block will have to be named differently!

    When you place a block, you'll have to use my script to save it's position. I recommend you put a script on each block that uses this:

    Code (CSharp):
    1.  
    2. public SaveInfoNewer SaveInfo;
    3.  
    4. //saves a key, the string is the name, the Vector3 is the position
    5. SaveInfo.data[this.gameObject.name] = this.gameObject.position;
    Instead of asking for a custom tutorial, first put in some effort, show what have you done and then ask how to solve a specific issue. It's like saying "Make me a hamburger", but I'll show you how to put on the bread, meat, tomatoes etc... so that you learn something and can write code independently.
     
  12. SubZeroGaming

    SubZeroGaming

    Joined:
    Mar 4, 2013
    Posts:
    1,008
    wow this dude is annoying...your status says The Best Coder At 4by4Studios

    FIGURE IT OUT YOURSELF OR GET SERIOUS BECAUSE IF YOU WANT THE PROS HELP YOU NEED TO PLAY BY THE PRO RULES
     
    DroidifyDevs likes this.
  13. DroidifyDevs

    DroidifyDevs

    Joined:
    Jun 24, 2015
    Posts:
    1,724
    Holy s*** I just noticed that he did say he's the best coder LOL

    Hey I'm not a great coder at all, but I'm starting to think I helped him too much...
     
    SubZeroGaming likes this.
  14. Benj4_

    Benj4_

    Joined:
    Nov 12, 2015
    Posts:
    38
    That's Because I'm The Only One Who Knows How To Code....
     
  15. SubZeroGaming

    SubZeroGaming

    Joined:
    Mar 4, 2013
    Posts:
    1,008
    BUT LIKE...YOU DON'T HAVE TO USE CAPS LIKE ME. yOU CAN TYPE NORMAL JUST LIKE YOU TYPE NORMAL WHEN YOU CODE. YOU FEEL? MAKES THE PROS MORE INCLINED TO HELP YOU, THE LESSER PRO.
     
  16. DroidifyDevs

    DroidifyDevs

    Joined:
    Jun 24, 2015
    Posts:
    1,724
    nah man, his code is all caps which is why it doesn't work :p
     
  17. SubZeroGaming

    SubZeroGaming

    Joined:
    Mar 4, 2013
    Posts:
    1,008
    lol. I'm done trolling this thread. I can't be asked to help if he's not going to be serious.
     
    DroidifyDevs likes this.
  18. DroidifyDevs

    DroidifyDevs

    Joined:
    Jun 24, 2015
    Posts:
    1,724
    Exactly. I already gave him quite a bit of code and ideas, and he hasn't even mentioned anything about it, apart from "make me a tutorial". But What Can You Expect From Someone Who Writes Like This.
     
  19. SubZeroGaming

    SubZeroGaming

    Joined:
    Mar 4, 2013
    Posts:
    1,008
    Seriously...It takes Effort To Write Like This And Its Just Annoying To Have CAPS LOCK ON SO EVERYTHING I SAY LOOKS LIKE THIS.
     
    DroidifyDevs likes this.