Write me a script in Unity that uses JSON to save and read user data (names, passwords, etc.) in C#.
时间: 2024-01-08 16:02:00 浏览: 98
Sure! Here's an example script that demonstrates how to use JSON to save and read user data in Unity using C#:
```
using UnityEngine;
using System.IO;
using System.Collections.Generic;
public class UserDataManager : MonoBehaviour
{
private string filePath;
private Dictionary<string, string> userData;
void Start()
{
filePath = Application.persistentDataPath + "/userdata.json";
LoadUserData();
}
public void SaveUserData(string username, string password)
{
if (userData.ContainsKey(username))
{
userData[username] = password;
}
else
{
userData.Add(username, password);
}
string dataAsJson = JsonUtility.ToJson(userData);
File.WriteAllText(filePath, dataAsJson);
}
public bool VerifyUserData(string username, string password)
{
if (userData.ContainsKey(username) && userData[username] == password)
{
return true;
}
return false;
}
private void LoadUserData()
{
if (File.Exists(filePath))
{
string dataAsJson = File.ReadAllText(filePath);
userData = JsonUtility.FromJson<Dictionary<string, string>>(dataAsJson);
}
else
{
userData = new Dictionary<string, string>();
}
}
}
```
Here's how to use this script:
1. Attach this script to a GameObject in your Unity scene.
2. Call `SaveUserData` to save a user's data. Pass in the user's username and password as parameters.
3. Call `VerifyUserData` to check if a user's data is valid. Pass in the user's username and password as parameters.
This script uses a dictionary to store user data, where the keys are usernames and the values are passwords. When `SaveUserData` is called, it checks if the username already exists in the dictionary. If it does, it updates the password. If it doesn't, it adds a new key-value pair to the dictionary. Then it serializes the dictionary to JSON and writes it to a file on disk.
When `VerifyUserData` is called, it checks if the username exists in the dictionary and if the password matches the value associated with that username.
The `LoadUserData` function is called in `Start` to read the saved user data from disk and deserialize it into the dictionary. If the file doesn't exist, it creates a new empty dictionary.
阅读全文