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

My Script's Load Section Doesn't Work.I Couldn't Find Why It Didn't Work

Discussion in 'Scripting' started by RedsonB, Apr 16, 2020.

  1. RedsonB

    RedsonB

    Joined:
    Apr 12, 2019
    Posts:
    7
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System.IO;
    5.  
    6. public class DataManager : MonoBehaviour
    7. {
    8.     public PlayerData data;
    9.  
    10.     private string file = "player.txt";
    11.  
    12.     public void Save()
    13.     {
    14.         string json = JsonUtility.ToJson(data);
    15.         WriteToFile(file, json);
    16.     }
    17.     public void Load()
    18.     {
    19.         Debug.Log("Load");
    20.         data = new PlayerData();
    21.         string json = ReadFromFile(file);
    22.         Debug.Log(file);
    23.  
    24.         JsonUtility.FromJsonOverwrite(json, data);
    25.      
    26.     }
    27.  
    28.     private void WriteToFile(string filename, string json)
    29.     {
    30.         string path = GetFilePath(filename);
    31.         FileStream fileStream = new FileStream(path, FileMode.Create);
    32.  
    33.         using (StreamWriter writer = new StreamWriter(fileStream))
    34.         {
    35.             writer.Write(json);
    36.  
    37.         }
    38.     }
    39.  
    40.     private string ReadFromFile(string filename)
    41.     {
    42.         string path = GetFilePath(filename);
    43.         if (File.Exists(path))
    44.         {
    45.             using (StreamReader reader=new StreamReader(path))
    46.             {
    47.                 string json = reader.ReadToEnd();
    48.                 return json;
    49.             }
    50.         }
    51.         else
    52.         {
    53.             Debug.LogWarning("File not found");
    54.         }
    55.         return "";
    56.     }
    57.  
    58.     private string GetFilePath(string filename)
    59.     {
    60.         return Application.persistentDataPath + "/" + filename;
    61.     }
    62. }
    63.  
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    So you can't be bothered to say what it is doing? For all I know you're just not calling Load(), since you're not doing so in any of the code you've posted.
     
  3. RedsonB

    RedsonB

    Joined:
    Apr 12, 2019
    Posts:
    7
    I am calling "Load()" in another script Start Section. But it's not working