Unity save class code example
Example: How to save custom class unity
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
[System.Serializable]
public class GameSettings
{
public float AudioVolume = .5f;
}
class AudioSettings : MonoBehaviour
{
private static AudioSettings _instance;
public static AudioSettings Instance { get { return _instance; } }
public GameSettings Gamer_Profile;
public string AppLocation => $"{Application.persistentDataPath}";
public string FileLocation => $"/Settings/";
public string FileName => $"gameSettings.json";
private void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(this.gameObject);
}
else
{
_instance = this;
}
Gamer_Profile = Loadprofile();
}
GameSettings SetData(float audioVol)
{
return new GameSettings
{
AudioVolume = audioVol
};
}
public GameSettings Loadprofile()
{
if (Directory.Exists($"{Application.persistentDataPath}/Settings/"))
{
if (File.Exists($"{Application.persistentDataPath}/Settings/gameSettings.json"))
{
string inputString = File.ReadAllText($"{Application.persistentDataPath}/Settings/gameSettings.json");
return JsonUtility.FromJson<GameSettings>(inputString);
}
}
Directory.CreateDirectory($"{Application.persistentDataPath}/Settings/");
return SetData(0.5f);
}
public void SaveProfile()
{
var outputString = JsonUtility.ToJson(Gamer_Profile);
if (!Directory.Exists($"{Application.persistentDataPath}/PlayerProfile/"))
{
Directory.CreateDirectory($"{Application.persistentDataPath}/PlayerProfile/");
}
File.WriteAllText($"{Application.persistentDataPath}/PlayerProfile/gameSettings.json", outputString);
}
}