using System.Collections.Generic; namespace UnityEngine.XR.Interaction.Toolkit.Utilities { /// /// Helper class that provides access to a shared instance created at runtime /// and destroys the instance when it is no longer in use. /// /// Type of ScriptableObject instance to provide. static class ScriptableSingletonCache where T : ScriptableObject { static T s_Instance; static readonly Dictionary> s_UsersPerInstance = new Dictionary>(); /// /// Gets a singleton instance of . This creates an instance if one does not already exist. /// /// Object using the singleton instance. /// Returns a singleton ScriptableObject instance of type . public static T GetInstance(object user) { if (s_Instance == null) s_Instance = ScriptableObject.CreateInstance(); if (!s_UsersPerInstance.TryGetValue(s_Instance, out var users)) { users = new HashSet(); s_UsersPerInstance.Add(s_Instance, users); } users.Add(user); return s_Instance; } /// /// Removes the given user object from access to the singleton instance of . This /// destroys the instance if no other objects are using it. /// /// Object no longer using the singleton instance. public static void ReleaseInstance(object user) { if (s_Instance == null) return; if (!s_UsersPerInstance.TryGetValue(s_Instance, out var users)) { Object.Destroy(s_Instance); return; } users.Remove(user); if (users.Count == 0) { s_UsersPerInstance.Remove(s_Instance); Object.Destroy(s_Instance); } } } }