using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
///
/// Keep track of all users
///
[CreateAssetMenu(menuName = "Create new Scriptable/UserList")]
public class UserList : ScriptableObject
{
///
/// Helper class to enable serialization of the UserList class
/// (ScriptableObjects cannot be serialized)
///
[Serializable]
public class StoredUserList
{
///
/// The index of the current/last logged in user in the storedUsers list
///
public int currentUserIndex;
///
/// A list containing all users (which can be serialized)
///
public List storedUsers = new List();
}
///
/// Reference to the serializable version of UserList
///
[SerializeField]
private StoredUserList storedUserList = new StoredUserList();
///
/// Path of the .json-file to store all serialized data
///
public static string PATH = null;
///
/// OnEnable will make sure the PATH-variable is correctly initialized
///
void OnEnable()
{
PATH = $"{Application.dataPath}/users.json";
Load();
}
///
/// Create a new user
///
/// The username of the new user
/// Reference to the user avatar
/// A newly created user
public User CreateNewUser(string name, Sprite avatar)
{
User user = new User();
user.username = name;
user.avatar = avatar;
return user;
}
///
/// Create a new user and save (add to list)
///
/// The username of the new user
/// Reference to the user avatar
/// A newly created user
public User CreateAndAddNewUser(string name, Sprite avatar)
{
User user = CreateNewUser(name, avatar);
storedUserList.storedUsers.Add(user);
Save();
return user;
}
///
/// Get a user by username
///
/// The username of the user
/// User-object if a user with such username was found, null otherwise
public User GetUserByUsername(string username)
{
foreach (User user in storedUserList.storedUsers)
if (user.username == username) return user;
return null;
}
///
/// Get a list of all users currently stored
///
/// A list of all users
public List GetUsers()
{
return storedUserList.storedUsers;
}
///
/// Get the current logged in user
///
/// The current logged in user
public User GetCurrentUser()
{
return storedUserList.storedUsers[storedUserList.currentUserIndex];
}
///
/// Save the users
///
public void Save()
{
string json = JsonUtility.ToJson(storedUserList);
File.CreateText(PATH).Close();
File.WriteAllText(PATH, json);
}
///
/// Override the current content of the userlist by what is stored on disk
///
public void Load()
{
try
{
storedUserList.storedUsers.Clear();
string text = File.ReadAllText(PATH);
storedUserList = JsonUtility.FromJson(text);
}
catch (FileNotFoundException) { Debug.Log($"Path '{PATH}' not found"); }
}
}