CodeBlanks Logo Icon CodeBlanks

Reading from a file

Learn to read saved data with File.ReadAllText.

File Checking and File.ReadAllText

Checking whether a file exists on disk with File.Exists(path) before reading prevents runtime exceptions. If verified, calling File.ReadAllText(path) retrieves the full file content as a string.

using System.IO;

if (File.Exists(path)) {
    string json = File.ReadAllText(path);
}

If the file is not found, a fresh profile initialized with default values can be created instead.

Deserialization: JsonUtility.FromJson

Rebuilding a live C# object from a retrieved JSON string is known as deserialization. The generic JsonUtility.FromJson<T>(json) method constructs an instance of type T and fills its fields.

// Restoring an object from a JSON string
PlayerData data = JsonUtility.FromJson<PlayerData>(json);
Debug.Log("Loaded health: " + data.health);

This seamlessly restores the player's health, score, and items back into active memory.

Practice Save file reading flow

Define a Start method. Inside, declare bool dosyaVar = true; and print "Kayit dosyasi bulundu: " + dosyaVar to the console.

Starter code

Player.cs
using UnityEngine;

public class SaveReader : MonoBehaviour
{
    // Start icinde dosyaVar degiskenini tanimla ve yazdir
}

Sample solution

Player.cs
using UnityEngine;

public class SaveReader : MonoBehaviour
{
    void Start()
    {
        bool dosyaVar = true;
        Debug.Log("Kayit dosyasi bulundu: " + dosyaVar);
    }
}

Expected output

Kayit dosyasi bulundu: True

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which method is used to safely verify the existence of a file before attempting to open it?

  • File.Find(path)
  • File.HasFile(path)
  • File.Exists(path) Correct answer
  • File.Validate(path)

Explanation: The System.IO.File.Exists(path) method returns a boolean (true/false) indicating whether a file exists at the given path.

2 Instantiate object from JSON

Question
PlayerData data = JsonUtility.____<PlayerData>(jsonString);
Answer
PlayerData data = JsonUtility.FromJson<PlayerData>(jsonString);

Explanation: The 'FromJson' method is invoked to convert JSON text into an instance of the specified C# type.

3 File reading concepts

Term Meaning
File.Exists Checks if the file exists on disk
File.ReadAllText Reads all text from the file
FromJson Converts JSON text into a C# object
Deserialization Process of restoring an object from text

All lessons in Advanced