// Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2024 Kybernetik // using System; using UnityEngine; using Object = UnityEngine.Object; namespace Animancer { /// /// Holds an instance of which is automatically created /// using its parameterless constructor when first accessed. /// /// /// Don't use classes that inherit from as . /// /// This is close to the "Singleton Programming Pattern", except it can't prevent additional instances of /// from being created elsewhere. /// /// https://kybernetik.com.au/animancer/api/Animancer/Static_1 public static class Static where T : class, new() { /************************************************************************************************************************/ /// /// An instance of which is automatically created /// using its parameterless constructor when first accessed. /// public static readonly T Instance = new(); /************************************************************************************************************************/ /// Ensures that the has been created without immediately using it. public static void Initialize() { } /************************************************************************************************************************/ #if UNITY_ASSERTIONS static Static() { if (Instance is Object) { Debug.LogError( $"{typeof(Static).GetNameCS()} type is invalid:" + $" {nameof(UnityEngine)}.{nameof(Object)} types require special memory management by Unity" + $" which may cause problems when used with this system.", Instance as Object); } } #endif /************************************************************************************************************************/ /// [Assert-Conditional] /// Call this in the constructor of to make sure there is only one instance. /// [System.Diagnostics.Conditional(Strings.Assertions)] public static void AssertSingularity() { #if UNITY_ASSERTIONS // If the static instance has already been set, then this is not the first one to be created. if (Instance != null) { var name = typeof(T).GetNameCS(); throw new InvalidOperationException( $"Multiple {name} objects have been created." + $"\nUse Static<{name}>.Instance instead of creating your own instances."); } #endif } /************************************************************************************************************************/ } }