You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中如何通过C#为JSON.txt设置默认高分及姓名值(防缺失/篡改)

Got it, let's tackle this high score JSON handling in Unity step by step. You need two key things: a fallback for when the file is missing or corrupted, and a way to set up default int/string values in the file. Here's how to do it properly:

1. Define Your High Score Data Structure

First, create a serializable C# class to map your JSON data. Unity's built-in JsonUtility works best with serializable types, so this will make serialization/deserialization straightforward:

using UnityEngine;

[Serializable]
public class HighScoreData
{
    public int score;
    public string playerName;
}

This class will correspond to JSON content like:

{
  "score": 1000,
  "playerName": "DefaultPlayer"
}
2. Core Logic: File Validation + Fallback to Defaults

Next, create a manager script to handle loading, validating, and saving the high score file. This script will check if the file exists, verify its content is valid, and fall back to default values if anything goes wrong.

using UnityEngine;
using System.IO;

public class HighScoreManager : MonoBehaviour
{
    private string highScoreFilePath;
    // Define your default values here
    private readonly HighScoreData defaultHighScore = new HighScoreData 
    { 
        score = 1000, 
        playerName = "DefaultPlayer" 
    };

    void Awake()
    {
        // Use Unity's persistent data path (cross-platform, writable)
        highScoreFilePath = Path.Combine(Application.persistentDataPath, "JSON.txt");
        LoadOrInitializeHighScore();
    }

    private void LoadOrInitializeHighScore()
    {
        HighScoreData loadedData = null;

        // Check if the file exists first
        if (File.Exists(highScoreFilePath))
        {
            try
            {
                // Read and deserialize the JSON content
                string jsonContent = File.ReadAllText(highScoreFilePath);
                loadedData = JsonUtility.FromJson<HighScoreData>(jsonContent);

                // Validate the data (prevent invalid tampering)
                if (IsDataInvalid(loadedData))
                {
                    Debug.LogWarning("High score data is corrupted — using default values.");
                    loadedData = defaultHighScore;
                }
            }
            catch (System.Exception e)
            {
                // Catch parsing errors (e.g., user messed up JSON format)
                Debug.LogError($"Failed to read high score file: {e.Message} — falling back to defaults.");
                loadedData = defaultHighScore;
            }
        }
        else
        {
            // File doesn't exist — create it with default values
            Debug.Log("High score file not found — creating default file.");
            loadedData = defaultHighScore;
        }

        // Save the valid data (ensures the file is always in a good state)
        SaveHighScore(loadedData);
        // You can assign loadedData to a public variable here for other scripts to use
        // e.g., public HighScoreData CurrentHighScore { get; private set; } = loadedData;
    }

    private bool IsDataInvalid(HighScoreData data)
    {
        // Add your validation rules here
        return data.score < 0 || string.IsNullOrEmpty(data.playerName);
    }

    private void SaveHighScore(HighScoreData data)
    {
        // Serialize the data to formatted JSON for readability
        string json = JsonUtility.ToJson(data, prettyPrint: true);
        File.WriteAllText(highScoreFilePath, json);
    }

    // Optional: Public method to update the high score safely
    public void UpdateHighScore(int newScore, string playerName)
    {
        if (!IsDataInvalid(new HighScoreData { score = newScore, playerName = playerName }))
        {
            SaveHighScore(new HighScoreData { score = newScore, playerName = playerName });
        }
        else
        {
            Debug.LogError("Invalid score or player name — cannot update high score.");
        }
    }
}
3. Key Details to Note
  • Cross-Platform Path: Application.persistentDataPath is the right choice here because it's a writable directory accessible on all Unity-supported platforms (PC, mobile, console).
  • Validation: The IsDataInvalid method lets you add custom rules (e.g., score can't exceed a max value, name can't be longer than 10 characters) to catch tampered data.
  • Error Handling: The try-catch block catches cases where the JSON is malformed (e.g., user deleted a bracket or changed the format).
  • Auto-Recovery: Whenever invalid/missing data is detected, the script immediately writes the default values back to the file, so subsequent runs will work correctly.
4. Testing It Out
  • First Run: The script will create JSON.txt in the persistent path with your default score and name.
  • Delete the File: Next run, the script will detect the missing file and generate a new one with defaults.
  • Tamper with Content: Edit the JSON to set score to -50 or playerName to an empty string — the script will flag it as invalid and overwrite with defaults.
Extra: Adding a Checksum (For Extra Security)

If you want to prevent advanced tampering, you can add a checksum to the JSON. For example, generate a hash of the score and name, store it in the data class, and verify it on load. This is optional but useful for competitive games.

内容的提问来源于stack exchange,提问作者Ruthl3ss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:18:10