using System; using System.Collections.Generic; using System.IO; using UnityEngine; [CreateAssetMenu(menuName = "Create new Scriptable/UserList")] public class UserList : ScriptableObject { // Serializable UserList content [Serializable] public class StoredUserList { public int currentUserIndex; public List storedUsers = new List(); } [Header("Users")] [SerializeField] // Reference to serializable version of UserList private StoredUserList storedUserList = new StoredUserList(); // Path to .json file public static string PATH = null; void OnEnable() { PATH = $"{Application.dataPath}/users.json"; Load(); } // Create a new 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 add to list public User CreateAndAddNewUser(string name, Sprite avatar) { User user = CreateNewUser(name, avatar); storedUserList.storedUsers.Add(user); Save(); return user; } // Get user by username, returns `null` if no user can be found with such name 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 public List GetUsers() { return storedUserList.storedUsers; } // Get the current active user public User GetCurrentUser() { return storedUserList.storedUsers[storedUserList.currentUserIndex]; } // Save the userList public void Save() { string json = JsonUtility.ToJson(storedUserList); File.CreateText(PATH).Close(); File.WriteAllText(PATH, json); } // Load the userList into this object public void Load() { try { storedUserList.storedUsers.Clear(); string text = File.ReadAllText(PATH); storedUserList = JsonUtility.FromJson(text); } catch (FileNotFoundException) { Debug.Log($"Path '{PATH}' not found"); } } }