using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; using UnityEngine; using UnityEngine.Assertions; namespace UDE_HAND_INTERACTION { public static class AssertManager { public const string HiglightColor = "#3366ff"; [Conditional("UNITY_ASSERTIONS")] public static void AssertField(this Component component, TValue value, string variableName, string whyItFailed = null, string whereItFailed = null, string howToFix = null) where TValue : class { string gameObjectName = component.name; string componentName = component.GetType().Name; string niceVariableName = Nicify(variableName); string variableType = typeof(TValue).Name; Assert.IsNotNull(value, (whereItFailed ?? $"At GameObject {gameObjectName}, component {componentName}. ") + (whyItFailed ?? $"Required {niceVariableName} reference is missing. ") + (howToFix ?? $"Assign a {variableType} to the field {niceVariableName}.")); } [Conditional("UNITY_ASSERTIONS")] public static void AssertCollectionItems(this Component component, IEnumerable value, string variableName, string whyItFailed = null, string whereItFailed = null, string howToFix = null) { string gameObjectName = component.name; string componentName = component.GetType().Name; string niceVariableName = Nicify(variableName); string variableType = typeof(TValue).Name; int index = 0; foreach (TValue item in value) { Assert.IsFalse(item is null, (whereItFailed ?? $"At GameObject {gameObjectName}, component {componentName}. ") + (whyItFailed ?? $"Invalid item in the collection {niceVariableName} at index {index}. ") + (howToFix ?? $"Assign a {variableType} to the collection {niceVariableName} at index {index}. ")); index++; } } [Conditional("UNITY_ASSERTIONS")] public static void AssertCollectionField(this Component component, IEnumerable value, string variableName, string whyItFailed = null, string whereFailed = null, string howToFix = null) { string gameObjectName = component.name; string componentName = component.GetType().Name; string niceVariableName = Nicify(variableName); string variableType = typeof(TValue).Name; Assert.IsTrue(value != null && value.Count() > 0, (whereFailed ?? $"At GameObject {gameObjectName}: the {componentName} component has an missing or empty {niceVariableName} collection. ") + (whyItFailed ?? "") + (howToFix ?? $"Assign at least one {variableType} to the collection {niceVariableName}. ")); component.AssertCollectionItems(value, variableName); } public static string Nicify(string variableName) { variableName = Regex.Replace(variableName, "_([a-z])", match => match.Value.ToUpper(), RegexOptions.Compiled); variableName = Regex.Replace(variableName, "m_|_", " ", RegexOptions.Compiled); variableName = Regex.Replace(variableName, "k([A-Z])", "$1", RegexOptions.Compiled); variableName = Regex.Replace(variableName, "([A-Z])", " $1", RegexOptions.Compiled); variableName = variableName.Trim(); return variableName; } } }