vardgrig

LevelController

Jun 30th, 2022 (edited)
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.17 KB | None | 0 0
  1. using System.Collections.Generic;
  2. using System.IO;
  3. using System.Runtime.Serialization.Formatters.Binary;
  4. using UnityEngine;
  5. using UnityEngine.SceneManagement;
  6.  
  7. public class LevelController : MonoBehaviour
  8. {
  9.     private int curScene;
  10.     public ObstacleController obstacleController;
  11.     public TextAsset level1;
  12.     public TextAsset level2;
  13.     public int levelIndex = 0;
  14.     public List<TextAsset> JsonList = new List<TextAsset>();
  15.  
  16.     void Start()
  17.     {
  18.         Debug.Log(Application.persistentDataPath + "/save.dat");
  19.         LoadFile();
  20.         SaveFile();
  21.     }
  22.     public void SaveFile()
  23.     {
  24.         string destination = Application.persistentDataPath + "/save.dat";
  25.         FileStream file;
  26.  
  27.         if (File.Exists(destination)) file = File.OpenWrite(destination);
  28.         else file = File.Create(destination);
  29.  
  30.         GameData data = new GameData(levelIndex);
  31.         BinaryFormatter bf = new BinaryFormatter();
  32.         bf.Serialize(file, data);
  33.         file.Close();
  34.     }
  35.  
  36.     public void LoadFile()
  37.     {
  38.         string destination = Application.persistentDataPath + "/save.dat";
  39.         FileStream file;
  40.  
  41.         if (File.Exists(destination)) file = File.OpenRead(destination);
  42.         else
  43.         {
  44.             Debug.LogError("File not found");
  45.             return;
  46.         }
  47.  
  48.         BinaryFormatter bf = new BinaryFormatter();
  49.         GameData data = bf.Deserialize(file) as GameData;
  50.         levelIndex = data.curLevel;
  51.         file.Close();
  52.  
  53.  
  54.         Debug.Log(data.curLevel);
  55.     }
  56.  
  57.     public void CreateJsonList()
  58.     {
  59.         JsonList.Add(level1);
  60.         JsonList.Add(level2);
  61.     }
  62.  
  63.     public void NextLevel()
  64.     {
  65.         if(levelIndex+1 < JsonList.Count)
  66.         {
  67.             ++levelIndex;
  68.             SaveFile();
  69.             SceneManager.LoadScene(SceneManager.GetActiveScene().name);
  70.             obstacleController.JSON = JsonList[levelIndex];
  71.         }
  72.     }
  73.     public void RestartLevel()
  74.     {
  75.         SceneManager.LoadScene(SceneManager.GetActiveScene().name);
  76.         obstacleController.JSON = JsonList[levelIndex];
  77.     }
  78.  
  79.     public void MainMenu()
  80.     {
  81.         SceneManager.LoadScene(0);
  82.     }
  83. }
  84.  
Add Comment
Please, Sign In to add comment