Consider this Unity C# code that saves a player's score to a file and then reads it back. What will be printed in the console?
using System.IO; using UnityEngine; public class SaveLoadExample : MonoBehaviour { void Start() { string path = Application.persistentDataPath + "/score.txt"; File.WriteAllText(path, "150"); string scoreText = File.ReadAllText(path); Debug.Log($"Score loaded: {scoreText}"); } }
Think about what File.WriteAllText and File.ReadAllText do.
The code writes the string "150" to the file, then reads it back and prints it. So the output is "Score loaded: 150".
In Unity, where should you save persistent game data to ensure it works on all platforms?
Look for the path meant for permanent data storage.
Application.persistentDataPath is the recommended location for saving files that should persist between app sessions on all platforms.
Look at this code snippet that tries to save player data. Why does it throw an exception?
using System.IO; using UnityEngine; public class SaveDebug : MonoBehaviour { void SaveScore(int score) { string path = Application.persistentDataPath + "/save.txt"; FileStream fs = new FileStream(path, FileMode.Open); StreamWriter writer = new StreamWriter(fs); writer.Write(score); writer.Close(); fs.Close(); } }
Check what happens if the file is missing when opening with FileMode.Open.
FileMode.Open requires the file to exist. If it doesn't, an exception is thrown. Use FileMode.Create or FileMode.OpenOrCreate to avoid this.
Given a PlayerData class, which code snippet correctly saves it as JSON to a file?
public class PlayerData { public int level; public float health; }
Remember the method to convert an object to JSON is ToJson.
JsonUtility.ToJson converts an object to a JSON string. Then File.WriteAllText saves it to a file. Other options misuse methods or use wrong functions.
This code saves multiple player profiles to separate files. How many files will be created after running it?
using System.IO; using UnityEngine; public class MultiSave : MonoBehaviour { void SaveProfiles() { for (int i = 0; i < 3; i++) { string path = Application.persistentDataPath + $"/player_{i}.json"; string json = JsonUtility.ToJson(new PlayerData { level = i, health = 100f }); File.WriteAllText(path, json); } } } public class PlayerData { public int level; public float health; }
Count how many times File.WriteAllText is called with different file names.
The loop runs 3 times, each time creating a file named player_0.json, player_1.json, and player_2.json. So 3 files are created.