diff --git a/Packages/Unity_Extensions/Scripts/AspectRatio.cs b/Packages/Unity_Extensions/Scripts/AspectRatio.cs index 2212586..a645bfe 100644 --- a/Packages/Unity_Extensions/Scripts/AspectRatio.cs +++ b/Packages/Unity_Extensions/Scripts/AspectRatio.cs @@ -3,13 +3,29 @@ namespace GG.Extensions { + /// + /// Provides utility methods for calculating aspect ratios. + /// public static class AspectRatio { + /// + /// Calculates the aspect ratio from given width and height integers. + /// + /// The width component of the resolution. + /// The height component of the resolution. + /// If true, logs the calculated aspect ratio to the console. + /// A Vector2 representing the aspect ratio (x:y). public static Vector2 GetAspectRatio(int x, int y, bool debug = false) { return GetAspectRatio(new Vector2(x, y), debug); } + /// + /// Calculates the aspect ratio from a Vector2 representing width and height. + /// + /// A Vector2 where x is width and y is height. + /// If true, logs the calculated aspect ratio to the console. + /// A Vector2 representing the aspect ratio (x:y). public static Vector2 GetAspectRatio(Vector2 xy, bool debug = false) { float f = xy.x / xy.y; @@ -22,8 +38,8 @@ public static Vector2 GetAspectRatio(Vector2 xy, bool debug = false) } if (debug) - Debug.Log("Aspect ratio is " + f * i + ":" + i + " (Resolution: " + xy.x + "x" + xy.y + ")"); + Debug.Log($"Aspect ratio is {f * i}:{i} (Resolution: {xy.x}x{xy.y})"); return new Vector2((float)System.Math.Round(f * i, 2), i); } } -} +} \ No newline at end of file diff --git a/Packages/Unity_Extensions/Scripts/CameraExtensions.cs b/Packages/Unity_Extensions/Scripts/CameraExtensions.cs index d7d7ce4..137c5da 100644 --- a/Packages/Unity_Extensions/Scripts/CameraExtensions.cs +++ b/Packages/Unity_Extensions/Scripts/CameraExtensions.cs @@ -5,67 +5,149 @@ namespace GG.Extensions { public static class CameraExtensions { - public static void LayerCullingShow(this Camera cam, int layerMask) { + /// + /// Shows layers specified by a bitmask on the camera's culling mask. + /// + /// The camera to modify. + /// The layer mask to show. + public static void LayerCullingShow(this Camera cam, int layerMask) + { cam.cullingMask |= layerMask; } - public static void LayerCullingShow(this Camera cam, string layer) { + /// + /// Shows a single layer specified by name on the camera's culling mask. + /// + /// The camera to modify. + /// The name of the layer to show. + public static void LayerCullingShow(this Camera cam, string layer) + { LayerCullingShow(cam, 1 << LayerMask.NameToLayer(layer)); } - + + /// + /// Shows multiple layers specified by names on the camera's culling mask. + /// + /// The camera to modify. + /// The names of the layers to show. public static void LayerCullingShow(this Camera camera, params string[] layerNames) { foreach (string layerName in layerNames) { - LayerCullingShow(camera,layerName); + LayerCullingShow(camera, layerName); } } - public static void LayerCullingHide(this Camera cam, int layerMask) { + /// + /// Hides layers specified by a bitmask from the camera's culling mask. + /// + /// The camera to modify. + /// The layer mask to hide. + public static void LayerCullingHide(this Camera cam, int layerMask) + { cam.cullingMask &= ~layerMask; } - public static void LayerCullingHide(this Camera cam, string layer) { + /// + /// Hides a single layer specified by name from the camera's culling mask. + /// + /// The camera to modify. + /// The name of the layer to hide. + public static void LayerCullingHide(this Camera cam, string layer) + { LayerCullingHide(cam, 1 << LayerMask.NameToLayer(layer)); } - + + /// + /// Hides multiple layers specified by names from the camera's culling mask. + /// + /// The camera to modify. + /// The names of the layers to hide. public static void LayerCullingHide(this Camera camera, params string[] layerNames) { foreach (string layerName in layerNames) { - LayerCullingHide(camera,layerName); + LayerCullingHide(camera, layerName); } } - public static void LayerCullingToggle(this Camera cam, int layerMask) { + /// + /// Toggles the visibility of layers specified by a bitmask on the camera's culling mask. + /// + /// The camera to modify. + /// The layer mask to toggle. + public static void LayerCullingToggle(this Camera cam, int layerMask) + { cam.cullingMask ^= layerMask; } - public static void LayerCullingToggle(this Camera cam, string layer) { + /// + /// Toggles the visibility of a single layer specified by name on the camera's culling mask. + /// + /// The camera to modify. + /// The name of the layer to toggle. + public static void LayerCullingToggle(this Camera cam, string layer) + { LayerCullingToggle(cam, 1 << LayerMask.NameToLayer(layer)); } - public static bool LayerCullingIncludes(this Camera cam, int layerMask) { + /// + /// Checks if the camera's culling mask includes layers specified by a bitmask. + /// + /// The camera to check. + /// The layer mask to check for inclusion. + /// True if the layer mask is included in the camera's culling mask; otherwise, false. + public static bool LayerCullingIncludes(this Camera cam, int layerMask) + { return (cam.cullingMask & layerMask) > 0; } - public static bool LayerCullingIncludes(this Camera cam, string layer) { + /// + /// Checks if the camera's culling mask includes a single layer specified by name. + /// + /// The camera to check. + /// The name of the layer to check for inclusion. + /// True if the layer is included in the camera's culling mask; otherwise, false. + public static bool LayerCullingIncludes(this Camera cam, string layer) + { return LayerCullingIncludes(cam, 1 << LayerMask.NameToLayer(layer)); } - public static void LayerCullingToggle(this Camera cam, int layerMask, bool isOn) { + /// + /// Toggles the visibility of layers specified by a bitmask on the camera's culling mask, with an option to force visibility on or off. + /// + /// The camera to modify. + /// The layer mask to toggle. + /// If true, forces the layer(s) to be visible; if false, forces the layer(s) to be hidden. + public static void LayerCullingToggle(this Camera cam, int layerMask, bool isOn) + { bool included = LayerCullingIncludes(cam, layerMask); - if (isOn && !included) { + if (isOn && !included) + { LayerCullingShow(cam, layerMask); - } else if (!isOn && included) { + } + else if (!isOn && included) + { LayerCullingHide(cam, layerMask); } } - public static void LayerCullingToggle(this Camera cam, string layer, bool isOn) { + /// + /// Toggles the visibility of a single layer specified by name on the camera's culling mask, with an option to force visibility on or off. + /// + /// The camera to modify. + /// The name of the layer to toggle. + /// If true, forces the layer to be visible; if false, forces the layer to be hidden. + public static void LayerCullingToggle(this Camera cam, string layer, bool isOn) + { LayerCullingToggle(cam, 1 << LayerMask.NameToLayer(layer), isOn); } + /// + /// Sets the camera's culling mask to show only the specified layers. + /// + /// The camera to modify. + /// A list of layer names to be made visible. public static void SetCullingMask(this Camera cam, List layers) { cam.cullingMask = 0; @@ -74,7 +156,14 @@ public static void SetCullingMask(this Camera cam, List layers) cam.LayerCullingShow(layer); } } - + + /// + /// Sets the camera's culling mask to show only the specified layer. + /// This method resets the camera's culling mask before showing the specified layer, + /// effectively making only the specified layer visible. + /// + /// The camera to modify. + /// The name of the layer to be made visible. public static void SetCullingMask(this Camera cam, string layer) { cam.cullingMask = 0; diff --git a/Packages/Unity_Extensions/Scripts/ColorExtensions.cs b/Packages/Unity_Extensions/Scripts/ColorExtensions.cs index cfedfc8..dc1f315 100644 --- a/Packages/Unity_Extensions/Scripts/ColorExtensions.cs +++ b/Packages/Unity_Extensions/Scripts/ColorExtensions.cs @@ -4,13 +4,25 @@ namespace GG.Extensions { public static class ColorExtensions { - // Note that Color32 and Color implictly convert to each other. You may pass a Color object to this method without first casting it. + /// + /// Converts a Color32 to a hexadecimal string representation. + /// + /// The Color32 to convert. + /// A hexadecimal string representing the color. public static string ColorToHex(this Color32 color) { string hex = color.r.ToString("X2") + color.g.ToString("X2") + color.b.ToString("X2"); return hex; } + /// + /// Converts a hexadecimal string to a Color. + /// + /// The hexadecimal string to convert. Can be prefixed with "0x" or "#". + /// A Color represented by the hexadecimal string. + /// + /// Assumes the color is fully opaque unless an alpha value is specified in the hex string. + /// public static Color HexToColor(string hex) { hex = hex.Replace("0x", ""); //in case the string is formatted 0xFFFFFF diff --git a/Packages/Unity_Extensions/Scripts/Colors.cs b/Packages/Unity_Extensions/Scripts/Colors.cs index 4312f19..2e4271e 100644 --- a/Packages/Unity_Extensions/Scripts/Colors.cs +++ b/Packages/Unity_Extensions/Scripts/Colors.cs @@ -4,8 +4,10 @@ namespace GG.Extensions { public class Colors { - // NOTE: The follwing color names come from the CSS3 specification, Section 4.3 Extended Color Keywords - // http://www.w3.org/TR/css3-color/#svg-color + /// + /// Generates a random color with each RGB component ranging from 0 to 1. + /// + /// A new Color instance with random RGB values. public static Color Random { get diff --git a/Packages/Unity_Extensions/Scripts/DateTimeExtensions.cs b/Packages/Unity_Extensions/Scripts/DateTimeExtensions.cs index 9628492..3b08da5 100644 --- a/Packages/Unity_Extensions/Scripts/DateTimeExtensions.cs +++ b/Packages/Unity_Extensions/Scripts/DateTimeExtensions.cs @@ -6,12 +6,21 @@ using System.Security.Cryptography; using System.Threading; using UnityEngine; + namespace GG.Extensions { -public static class DateTimeExtensions + public static class DateTimeExtensions { + /// + /// Represents the Unix epoch start date. + /// public static readonly DateTime UNIXTIME_ZERO_POINT = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + /// + /// Converts an integer to its ordinal suffix (e.g., "1" to "1st", "2" to "2nd"). + /// + /// The integer to convert. + /// The ordinal suffix for the given integer. public static string ToOccurrenceSuffix(this int integer) { switch (integer % 100) @@ -21,6 +30,7 @@ public static string ToOccurrenceSuffix(this int integer) case 13: return "th"; } + switch (integer % 10) { case 1: @@ -33,16 +43,24 @@ public static string ToOccurrenceSuffix(this int integer) return "th"; } } - + + /// + /// Converts a DateTime object to a string representation using specified format. + /// Supports extended specifiers for day occurrence suffixes ("nn" for lowercase, "NN" for uppercase). + /// + /// The DateTime object to format. + /// The format string. + /// Whether to use extended day occurrence suffixes. + /// A formatted string representation of the DateTime object. public static string ToString(this DateTime dateTime, string format, bool useExtendedSpecifiers) { - return useExtendedSpecifiers - ? dateTime.ToString(format) - .Replace("nn", dateTime.Day.ToOccurrenceSuffix().ToLower()) - .Replace("NN", dateTime.Day.ToOccurrenceSuffix().ToUpper()) - : dateTime.ToString(format); - - } + return useExtendedSpecifiers + ? dateTime.ToString(format) + .Replace("nn", dateTime.Day.ToOccurrenceSuffix().ToLower()) + .Replace("NN", dateTime.Day.ToOccurrenceSuffix().ToUpper()) + : dateTime.ToString(format); + } + /// /// Converts a Unix timestamp (UTC timezone by definition) into a DateTime object /// @@ -79,14 +97,20 @@ public static long ToUnixtime(this DateTime value, bool isInMilliseconds = false { if (isInMilliseconds) { - return (long) value.ToUniversalTime().Subtract(UNIXTIME_ZERO_POINT).TotalMilliseconds; + return (long)value.ToUniversalTime().Subtract(UNIXTIME_ZERO_POINT).TotalMilliseconds; } else { - return (long) value.ToUniversalTime().Subtract(UNIXTIME_ZERO_POINT).TotalSeconds; + return (long)value.ToUniversalTime().Subtract(UNIXTIME_ZERO_POINT).TotalSeconds; } } + /// + /// Rounds up the given DateTime to the nearest interval specified by the TimeSpan. + /// + /// The DateTime to round up. + /// The TimeSpan interval to round up to. + /// A new DateTime rounded up to the nearest interval. public static DateTime RoundUp(this DateTime dt, TimeSpan d) { var modTicks = dt.Ticks % d.Ticks; @@ -94,12 +118,24 @@ public static DateTime RoundUp(this DateTime dt, TimeSpan d) return new DateTime(dt.Ticks + delta, dt.Kind); } + /// + /// Rounds down the given DateTime to the nearest interval specified by the TimeSpan. + /// + /// The DateTime to round down. + /// The TimeSpan interval to round down to. + /// A new DateTime rounded down to the nearest interval. public static DateTime RoundDown(this DateTime dt, TimeSpan d) { var delta = dt.Ticks % d.Ticks; return new DateTime(dt.Ticks - delta, dt.Kind); } + /// + /// Rounds the given DateTime to the nearest interval specified by the TimeSpan, either up or down. + /// + /// The DateTime to round. + /// The TimeSpan interval to round to. + /// A new DateTime rounded to the nearest interval. public static DateTime RoundToNearest(this DateTime dt, TimeSpan d) { var delta = dt.Ticks % d.Ticks; @@ -109,28 +145,34 @@ public static DateTime RoundToNearest(this DateTime dt, TimeSpan d) return new DateTime(dt.Ticks + offset - delta, dt.Kind); } + /// + /// Finds the start of the week for the given DateTime, based on the specified first day of the week. + /// + /// The DateTime to find the start of the week for. + /// The day considered as the first day of the week. + /// A new DateTime representing the start of the week. public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek) { int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7; return dt.AddDays(-1 * diff).Date; } - + /// - /// get the datetime of the start of the month - /// - /// - /// - /// http://stackoverflow.com/a/5002582/428061 - public static System.DateTime StartOfMonth(this System.DateTime dt) => - new System.DateTime(dt.Year, dt.Month, 1); - + /// get the datetime of the start of the month + /// + /// + /// + /// http://stackoverflow.com/a/5002582/428061 + public static System.DateTime StartOfMonth(this System.DateTime dt) => + new System.DateTime(dt.Year, dt.Month, 1); + /// - /// get datetime of the start of the year - /// - /// - /// - public static System.DateTime StartOfYear(this System.DateTime dt) => - new System.DateTime(dt.Year, 1, 1); + /// get datetime of the start of the year + /// + /// + /// + public static System.DateTime StartOfYear(this System.DateTime dt) => + new System.DateTime(dt.Year, 1, 1); /// /// Gets the current week number for a specified DateTime object. @@ -139,15 +181,31 @@ public static System.DateTime StartOfYear(this System.DateTime dt) => /// public static int GetCurrentWeekNumber(this DateTime dateTime) { - int weekOfYear = Thread.CurrentThread.CurrentCulture.Calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday); + int weekOfYear = + Thread.CurrentThread.CurrentCulture.Calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstFullWeek, + DayOfWeek.Monday); return weekOfYear; } + /// + /// Checks if a given date is within a specified date range. + /// + /// The date to check. + /// The start date of the range. + /// The end date of the range. + /// True if the date is within the range, false otherwise. public static bool InRange(this DateTime dateToCheck, DateTime startDate, DateTime endDate) { return dateToCheck >= startDate && dateToCheck < endDate; } + /// + /// Retrieves all dates within a specified month and year from a list of dates. + /// + /// The list of dates to filter. + /// The month to filter by. + /// The year to filter by. + /// A list of dates that fall within the specified month and year. public static List AllDatesInMonth(this List dateTime, int month, int year) { DateTime firstOftargetMonth = new DateTime(year, month, 1); @@ -165,6 +223,13 @@ public static List AllDatesInMonth(this List dateTime, int m return allDates; } + /// + /// Generates a list of random dates within a specified date range. + /// + /// The start date of the range. + /// The end date of the range. + /// The number of random dates to generate. + /// A list of random dates within the specified range. public static IList GetRandomDates(DateTime startDate, DateTime maxDate, int range) { int[] randomResult = GetRandomNumbers(range).ToArray(); @@ -174,6 +239,11 @@ public static IList GetRandomDates(DateTime startDate, DateTime maxDat return dateResults; } + /// + /// Generates a sequence of random numbers. + /// + /// The number of random numbers to generate. + /// An enumerable of random numbers. static IEnumerable GetRandomNumbers(int size) { byte[] data = new byte[4]; @@ -189,11 +259,21 @@ static IEnumerable GetRandomNumbers(int size) } } + /// + /// Converts a string representation of a date to its DateTime equivalent using a specified format and culture string. + /// + /// The string representation of the date to convert. + /// The format of the date string. Defaults to "ddMMyyyy". + /// The culture identifier string. Defaults to "en-GB". + /// The DateTime equivalent of the string representation. + /// Thrown when the string is not in the specified format. + /// Thrown when the specified culture is not supported. public static DateTime ToDateTime(this string s, string format = "ddMMyyyy", string cultureString = "en-GB") { try { - DateTime r = DateTime.ParseExact(s: s, format: format, provider: CultureInfo.GetCultureInfo(cultureString)); + DateTime r = DateTime.ParseExact(s: s, format: format, + provider: CultureInfo.GetCultureInfo(cultureString)); return r; } catch (FormatException) @@ -206,6 +286,15 @@ public static DateTime ToDateTime(this string s, string format = "ddMMyyyy", str } } + /// + /// Converts a string representation of a date to its DateTime equivalent using a specified format and CultureInfo. + /// + /// The string representation of the date to convert. + /// The format of the date string. + /// The CultureInfo object representing the culture. + /// The DateTime equivalent of the string representation. + /// Thrown when the string is not in the specified format. + /// Thrown when the specified culture is not supported. public static DateTime ToDateTime(this string s, string format, CultureInfo culture) { try @@ -221,7 +310,6 @@ public static DateTime ToDateTime(this string s, string format, CultureInfo cult { throw; // Given Culture is not supported culture } - } } -} +} \ No newline at end of file diff --git a/Packages/Unity_Extensions/Scripts/EnumExtensions.cs b/Packages/Unity_Extensions/Scripts/EnumExtensions.cs index 9376cb4..3d93447 100644 --- a/Packages/Unity_Extensions/Scripts/EnumExtensions.cs +++ b/Packages/Unity_Extensions/Scripts/EnumExtensions.cs @@ -23,7 +23,8 @@ public static string GetDescription(this T value) FieldInfo field = typeof(T).GetField(name); if (field != null) { - DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; + DescriptionAttribute attr = + Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; if (attr != null) { return attr.Description; @@ -33,7 +34,7 @@ public static string GetDescription(this T value) return null; } - + /// /// Returns the description assigned to the enum value throguh system.componentmodel, /// Use this when passing a generic object though thats an enum @@ -47,13 +48,15 @@ public static string GetDescriptionFromObject(this object o) { throw new ArgumentException(string.Format("Type '{0}' is not an enum", o.GetType())); } + string name = Enum.GetName(o.GetType(), o); if (name != null) { FieldInfo field = o.GetType().GetField(name); if (field != null) { - DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; + DescriptionAttribute attr = + Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; if (attr != null) { return attr.Description; @@ -63,7 +66,12 @@ public static string GetDescriptionFromObject(this object o) return null; } - + + /// + /// Retrieves descriptions for all enum values of a specified type. + /// + /// The enum type. + /// An enumerable of descriptions for each enum value. public static IEnumerable GetDescriptions() { List descs = new List(); @@ -71,9 +79,17 @@ public static IEnumerable GetDescriptions() { descs.Add(GetDescription(item)); } + return descs; } - + + /// + /// Finds an enum value by its description. + /// + /// The enum type. + /// The description to search for. + /// The enum value associated with the given description, or the default value if not found. + /// Thrown if T is not an enum type. public static T GetEnumValueFromDescription(string description) { var type = typeof(T); @@ -84,18 +100,32 @@ public static T GetEnumValueFromDescription(string description) .SelectMany(f => f.GetCustomAttributes( typeof(DescriptionAttribute), false), ( f, a) => new { Field = f, Att = a }).SingleOrDefault(a => ((DescriptionAttribute)a.Att) - .Description == description); + .Description == description); return field == null ? default(T) : (T)field.Field.GetRawConstantValue(); } + /// + /// Validates that a type is an enum and optionally checks for the Flags attribute. + /// + /// The type to check. + /// Whether to check for the Flags attribute. + /// Thrown if T is not an enum or doesn't have the Flags attribute when required. private static void CheckIsEnum(bool withFlags) { if (!typeof(T).IsEnum) throw new ArgumentException(string.Format("Type '{0}' is not an enum", typeof(T).FullName)); if (withFlags && !Attribute.IsDefined(typeof(T), typeof(FlagsAttribute))) - throw new ArgumentException(string.Format("Type '{0}' doesn't have the 'Flags' attribute", typeof(T).FullName)); + throw new ArgumentException(string.Format("Type '{0}' doesn't have the 'Flags' attribute", + typeof(T).FullName)); } + /// + /// Checks if a specific flag is set in an enum value. + /// + /// The enum type. + /// The enum value to check. + /// The flag to check for. + /// True if the flag is set, false otherwise. public static bool IsFlagSet(this T value, T flag) where T : struct { CheckIsEnum(true); @@ -104,6 +134,12 @@ public static bool IsFlagSet(this T value, T flag) where T : struct return (lValue & lFlag) != 0; } + /// + /// Retrieves all flags that are set in an enum value. + /// + /// The enum type. + /// The enum value to check. + /// An enumerable of all set flags. public static IEnumerable GetFlags(this T value) where T : struct { CheckIsEnum(true); @@ -128,21 +164,48 @@ public static T SetFlags(this T value, T flags, bool on) where T : struct lValue &= (~lFlag); } - return (T) Enum.ToObject(typeof(T), lValue); + return (T)Enum.ToObject(typeof(T), lValue); } + /// + /// Joins the specified flags with the current value, setting the specified flags to true. + /// + /// The enum type. + /// The current enum value. + /// The flags to join with the current value. + /// The result of joining the specified flags with the current value. public static T JoinFlags(this T value, T flags) where T : struct => value.SetFlags(flags, true); + /// + /// Sets the specified flags on the current value. + /// + /// The enum type. + /// The current enum value. + /// The flags to set. + /// The result of setting the specified flags on the current value. public static T SetFlags(this T value, T flags) where T : struct { return value.SetFlags(flags, true); } + /// + /// Clears the specified flags from the current value. + /// + /// The enum type. + /// The current enum value. + /// The flags to clear. + /// The result of clearing the specified flags from the current value. public static T ClearFlags(this T value, T flags) where T : struct { return value.SetFlags(flags, false); } + /// + /// Combines multiple enum flags into a single value. + /// + /// The enum type. + /// The collection of enum flags to combine. + /// The combined enum value. public static T CombineFlags(this IEnumerable flags) where T : struct { CheckIsEnum(true); @@ -153,14 +216,20 @@ public static T CombineFlags(this IEnumerable flags) where T : struct lValue |= lFlag; } - return (T) Enum.ToObject(typeof(T), lValue); + return (T)Enum.ToObject(typeof(T), lValue); } + /// + /// Cycles through the values of an enum, moving to the next value, and wrapping back to the first value after the last. + /// + /// The enum type. + /// The current enum value. + /// The next enum value, or the first enum value if the current value is the last. public static T CycleEnum(this T enumerable) where T : struct, IConvertible { int enumLength = Enum.GetValues(typeof(T)).Length; - int val = (int) (IConvertible) enumerable; + int val = (int)(IConvertible)enumerable; val++; if (val == enumLength) @@ -168,14 +237,19 @@ public static T CycleEnum(this T enumerable) where T : struct, IConvertible val = 0; } - T returnVal = (T) (IConvertible) val; + T returnVal = (T)(IConvertible)val; return returnVal; } - + + /// + /// Converts the enum values to a list of their names. + /// + /// The enum type. + /// A list of the names of the enum values. public static List AsList() where T : struct, Enum { return Enum.GetNames(typeof(T)).ToList(); } } -} +} \ No newline at end of file diff --git a/Packages/Unity_Extensions/Scripts/FileExtensions.cs b/Packages/Unity_Extensions/Scripts/FileExtensions.cs index 240e46d..c6723ca 100644 --- a/Packages/Unity_Extensions/Scripts/FileExtensions.cs +++ b/Packages/Unity_Extensions/Scripts/FileExtensions.cs @@ -6,28 +6,37 @@ namespace GG.Extensions { public static class FileExtensions { - public static bool IsFileInUse(FileInfo file) - { - FileStream stream = null; + /// +/// Checks if the specified file is currently in use by another process. +/// +/// The FileInfo object representing the file to check. +/// True if the file is in use; otherwise, false. +/// +/// This method attempts to open the file with read/write access and no sharing. +/// If an IOException is caught, it is assumed the file is in use. +/// The file stream is closed immediately in the finally block if it was successfully opened. +/// +public static bool IsFileInUse(FileInfo file) +{ + FileStream stream = null; - try - { - stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); - } - catch (IOException) - { - //the file is unavailable because it is: - //still being written to - //or being processed by another thread - //or does not exist (has already been processed) - return true; - } - finally - { - stream?.Close(); - } - return false; - } + try + { + // Attempt to open the file with exclusive access. + stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); + } + catch (IOException) + { + // IOException caught indicates the file is in use or does not exist. + return true; + } + finally + { + // Ensure the file stream is closed if it was opened. + stream?.Close(); + } + return false; +} /// /// Copy a whole directory with option to copy all sub folders @@ -74,10 +83,15 @@ public static void DirectoryCopy(string sourceDirName, string destDirName, bool } } - public static string RemoveFileExtension(string filePath) - { - return Path.ChangeExtension(filePath, null); - } +/// +/// Removes the file extension from a given file path. +/// +/// The full path of the file including its extension. +/// The file path without its extension. +public static string RemoveFileExtension(string filePath) +{ + return Path.ChangeExtension(filePath, null); +} /// /// Determine whether a given path is a directory. diff --git a/Packages/Unity_Extensions/Scripts/GameObjectExtensions.cs b/Packages/Unity_Extensions/Scripts/GameObjectExtensions.cs index 40cd86f..60c6914 100644 --- a/Packages/Unity_Extensions/Scripts/GameObjectExtensions.cs +++ b/Packages/Unity_Extensions/Scripts/GameObjectExtensions.cs @@ -7,108 +7,140 @@ namespace GG.Extensions public static class GameObjectExtensions { static List dontDestoryOnLoadObjects = new List(); + + /// + /// Gets an existing component of type T from the child or adds one if it doesn't exist. + /// + /// The type of the component to get or add. + /// The component from which to get or add the component. + /// The existing or newly added component. + static public T GetOrAddComponent(this Component child) where T : Component + { + T result = child.GetComponent(); + if (result == null) + { + result = child.gameObject.AddComponent(); + } + return result; + } + + /// + /// Gets an existing component of type T from the GameObject or adds one if it doesn't exist. + /// + /// The type of the component to get or add. + /// The GameObject from which to get or add the component. + /// The existing or newly added component. + static public T GetOrAddComponent(this GameObject child) where T : Component + { + return GetOrAddComponent(child.transform); + } + + /// + /// Changes the material of all Renderer components in the GameObject and its children. + /// + /// The GameObject whose materials to change. + /// The new material to apply. + public static void ChangeMaterial(this GameObject go, Material newMat) + { + Renderer[] children = go.GetComponentsInChildren(true); + foreach (Renderer rend in children) + { + Material[] mats = new Material[rend.materials.Length]; + for (int j = 0; j < rend.materials.Length; j++) + { + mats[j] = newMat; + } + rend.materials = mats; + } + } + + /// + /// Gets a component of type T from the parent of the GameObject, ignoring any components of type T on the GameObject itself. + /// + /// The type of the component to get. + /// The GameObject from which to start the search. + /// The component of type T from the parent GameObject. + public static T GetComponentInParentIgnoreSelf(this GameObject go) + { + return go.transform.parent.GetComponentInParent(); + } /// - /// Gets or add a component. Usage example: - /// BoxCollider boxCollider = transform.GetOrAddComponent(); - /// - static public T GetOrAddComponent(this Component child) where T : Component - { - T result = child.GetComponent(); - if (result == null) - { - result = child.gameObject.AddComponent(); - } - return result; - } - - /// - /// Gets or add a component. Usage example: - /// BoxCollider boxCollider = transform.GetOrAddComponent(); - /// - /// - /// - /// - static public T GetOrAddComponent(this GameObject child) where T : Component - { - return GetOrAddComponent(child.transform); - } - - public static void ChangeMaterial(this GameObject go, Material newMat) - { - Renderer[] children = go.GetComponentsInChildren(true); - foreach (Renderer rend in children) - { - Material[] mats = new Material[rend.materials.Length]; - for (int j = 0; j < rend.materials.Length; j++) - { - mats[j] = newMat; - } - rend.materials = mats; - } - } - - public static T GetComponentInParentIgnoreSelf(this GameObject go) - { - return go.transform.parent.GetComponentInParent(); - } - - /// - /// Use this for dont destory on load to keep referances for the find object of type all - /// - /// - public static void DontDestroyOnLoad(this GameObject obj) - { - dontDestoryOnLoadObjects.Add(obj); - Object.DontDestroyOnLoad(obj); - } - - public static void DestoryDontDestroyOnLoad(this GameObject obj) - { - dontDestoryOnLoadObjects.Remove(obj); - Object.Destroy(obj); - } - - public static List GetDontDestroyOnLoadObjects() - { - dontDestoryOnLoadObjects = dontDestoryOnLoadObjects.Where(x => x != null).ToList(); - return new List(dontDestoryOnLoadObjects); - } - - /// - /// Return a list of all child objects - /// - /// - /// - public static List GetAllChildren(this GameObject gameObject) - { - Transform[] childTransforms = gameObject.GetComponentsInChildren(); - List allChildren = new List(childTransforms.Length); +/// Marks the specified GameObject to not be destroyed when loading a new scene. +/// +/// The GameObject to preserve across scenes. +/// +/// Adds the GameObject to a static list to keep track of objects that shouldn't be destroyed on load. +/// +public static void DontDestroyOnLoad(this GameObject obj) +{ + dontDestoryOnLoadObjects.Add(obj); + Object.DontDestroyOnLoad(obj); +} - foreach(Transform child in childTransforms) - { - if(child.gameObject != gameObject) allChildren.Add(child.gameObject); - } +/// +/// Destroys a GameObject that was previously marked with DontDestroyOnLoad. +/// +/// The GameObject to destroy. +/// +/// Removes the GameObject from the static list that tracks objects preserved across scenes before destroying it. +/// +public static void DestoryDontDestroyOnLoad(this GameObject obj) +{ + dontDestoryOnLoadObjects.Remove(obj); + Object.Destroy(obj); +} - return allChildren; - } +/// +/// Retrieves a list of all GameObjects that have been marked to not be destroyed on scene loads. +/// +/// A list of GameObjects that are preserved across scenes. +/// +/// Filters out any null references in the static list before returning it to ensure all returned objects are valid. +/// +public static List GetDontDestroyOnLoadObjects() +{ + dontDestoryOnLoadObjects = dontDestoryOnLoadObjects.Where(x => x != null).ToList(); + return new List(dontDestoryOnLoadObjects); +} - /// - /// Return a list of all child objects including itself - /// - /// - /// - public static List GetAllChildrenAndSelf(this GameObject gameObject) - { - Transform[] childTransforms = gameObject.GetComponentsInChildren(); - List allChildren = new List(childTransforms.Length); +/// +/// Returns a list of all child GameObjects of the specified GameObject. +/// +/// The parent GameObject. +/// A list of all child GameObjects. +/// +/// Does not include the parent GameObject in the list, only its children. +/// +public static List GetAllChildren(this GameObject gameObject) +{ + Transform[] childTransforms = gameObject.GetComponentsInChildren(); + List allChildren = new List(childTransforms.Length); - for (int transformIndex = 0; transformIndex < childTransforms.Length; ++transformIndex) - { - allChildren.Add(childTransforms[transformIndex].gameObject); - } + foreach(Transform child in childTransforms) + { + if(child.gameObject != gameObject) allChildren.Add(child.gameObject); + } - return allChildren; - } + return allChildren; +} + +/// +/// Returns a list of all child GameObjects of the specified GameObject, including the GameObject itself. +/// +/// The GameObject to retrieve children from. +/// A list of GameObjects representing all children and the GameObject itself. +public static List GetAllChildrenAndSelf(this GameObject gameObject) +{ + Transform[] childTransforms = gameObject.GetComponentsInChildren(); + List allChildren = new List(childTransforms.Length); + + for (int transformIndex = 0; transformIndex < childTransforms.Length; ++transformIndex) + { + allChildren.Add(childTransforms[transformIndex].gameObject); + } + + return allChildren; +} } } diff --git a/Packages/Unity_Extensions/Scripts/ImageExtensions.cs b/Packages/Unity_Extensions/Scripts/ImageExtensions.cs index b533bee..5bc07f5 100644 --- a/Packages/Unity_Extensions/Scripts/ImageExtensions.cs +++ b/Packages/Unity_Extensions/Scripts/ImageExtensions.cs @@ -9,11 +9,15 @@ namespace GG.Extensions public static class ImageExtensions { /// - /// Generate a texture from base64 string + /// Generates a Texture2D object from a base64 encoded string. /// - /// - /// - /// + /// The base64 encoded string representing the image data. + /// Optional name to assign to the texture. Defaults to an empty string. + /// A new Texture2D object created from the base64 string. + /// + /// The texture is created with a default size of 16x16 pixels, ARGB32 format, no mipmaps, and bilinear filtering. + /// The texture is also marked with HideFlags.HideAndDontSave to avoid it being saved with the scene. + /// public static Texture2D CreateTextureFromBase64(string base64, string name = "") { byte[] data = Convert.FromBase64String(base64); @@ -22,6 +26,15 @@ public static Texture2D CreateTextureFromBase64(string base64, string name = "") return tex; } + /// + /// Creates a Sprite from a base64 encoded string. + /// + /// The base64 encoded string representing the image data. + /// A new Sprite created from the base64 string. + /// + /// This method first converts the base64 string into a Texture2D object, then creates a sprite from the entire texture. + /// The sprite's pivot is set to the center (0.5, 0.5) and pixels per unit to 100. + /// public static Sprite CreateSpriteFromBase64(string base64) { Texture2D tex = CreateTextureFromBase64(base64); @@ -29,10 +42,13 @@ public static Sprite CreateSpriteFromBase64(string base64) } /// - /// convert a texture to base 64 string + /// Converts a Texture2D object to a base64 encoded string. /// - /// - /// + /// The Texture2D object to convert. + /// A base64 encoded string representing the image data of the Texture2D. + /// + /// The texture is first encoded to PNG format before being converted to a base64 string. + /// public static string ToBase64Image(Texture2D texture2D) { byte[] imageData = texture2D.EncodeToPNG(); @@ -40,19 +56,30 @@ public static string ToBase64Image(Texture2D texture2D) } /// - /// Convert image file to base64 string + /// Converts an image file to a base64 encoded string. /// - /// - /// + /// The file path of the image to convert. + /// A base64 encoded string representing the image data. + /// + /// The image file is read as a byte array before being converted to a base64 string. + /// public static string ToBase64Image(string path) { byte[] asBytes = File.ReadAllBytes(path); return Convert.ToBase64String(asBytes); } + /// + /// Loads an image file as a byte array. + /// + /// The file path of the image to load. + /// A byte array containing the image data. + /// + /// This method directly reads the file content into a byte array without any conversion. + /// public static byte[] LoadImageAsBytes(string path) { return File.ReadAllBytes(path); } } -} +} \ No newline at end of file diff --git a/Packages/Unity_Extensions/Scripts/Input/InputExtensions.cs b/Packages/Unity_Extensions/Scripts/Input/InputExtensions.cs index 6610de3..8c34d4b 100644 --- a/Packages/Unity_Extensions/Scripts/Input/InputExtensions.cs +++ b/Packages/Unity_Extensions/Scripts/Input/InputExtensions.cs @@ -2,6 +2,9 @@ namespace GG.Extensions { + /// + /// Defines the types of input devices. + /// public enum DeviceType { Gamepad, @@ -14,8 +17,16 @@ public enum DeviceType Unknown } + /// + /// Provides extension methods for input-related functionalities. + /// public static class InputExtensions { + /// + /// Determines the type of device from an input action callback context. + /// + /// The callback context from which to determine the device type. + /// The determined device type. public static DeviceType GetDeviceType(InputAction.CallbackContext context) { InputDevice device = context.control.device; @@ -54,6 +65,13 @@ public static DeviceType GetDeviceType(InputAction.CallbackContext context) } } + /// + /// Tries to read the value of the specified type from an input action callback context. + /// + /// The type of the value to read. + /// The callback context from which to read the value. + /// The output parameter that will contain the read value if successful. + /// True if the value was successfully read; otherwise, false. public static bool TryReadValue(this InputAction.CallbackContext context, out T value) where T : struct { // Initialize the output value to the default diff --git a/Packages/Unity_Extensions/Scripts/LayerMaskExtensions.cs b/Packages/Unity_Extensions/Scripts/LayerMaskExtensions.cs index 5f55f3a..3c154c5 100644 --- a/Packages/Unity_Extensions/Scripts/LayerMaskExtensions.cs +++ b/Packages/Unity_Extensions/Scripts/LayerMaskExtensions.cs @@ -9,16 +9,31 @@ namespace GG.Extensions { public static class LayerMaskExtensions { + /// + /// Creates a LayerMask from an array of layer names. + /// + /// Array of layer names to include in the mask. + /// A LayerMask composed of the specified layers. public static LayerMask CreateLayerMask(params string[] layerNames) { return NamesToMask(layerNames); } + /// + /// Creates a LayerMask from an array of layer numbers. + /// + /// Array of layer numbers to include in the mask. + /// A LayerMask composed of the specified layers. public static LayerMask CreateLayerMask(params int[] layerNumbers) { return LayerNumbersToMask(layerNumbers); } + /// + /// Converts an array of layer names into a LayerMask. + /// + /// Array of layer names to convert. + /// A LayerMask representing the given layer names. public static LayerMask NamesToMask(params string[] layerNames) { LayerMask ret = 0; @@ -30,6 +45,11 @@ public static LayerMask NamesToMask(params string[] layerNames) return ret; } + /// + /// Converts an array of layer numbers into a LayerMask. + /// + /// Array of layer numbers to convert. + /// A LayerMask representing the given layer numbers. public static LayerMask LayerNumbersToMask(params int[] layerNumbers) { LayerMask ret = 0; @@ -41,22 +61,44 @@ public static LayerMask LayerNumbersToMask(params int[] layerNumbers) return ret; } + /// + /// Inverts the given LayerMask. + /// + /// The original LayerMask to invert. + /// An inverted LayerMask. public static LayerMask Inverse(this LayerMask original) { return ~original; } + /// + /// Adds layers to the given LayerMask. + /// + /// The original LayerMask to add layers to. + /// Array of layer names to add. + /// A LayerMask with the specified layers added. public static LayerMask AddToMask(this LayerMask original, params string[] layerNames) { return original | NamesToMask(layerNames); } + /// + /// Removes layers from the given LayerMask. + /// + /// The original LayerMask to remove layers from. + /// Array of layer names to remove. + /// A LayerMask with the specified layers removed. public static LayerMask RemoveFromMask(this LayerMask original, params string[] layerNames) { LayerMask invertedOriginal = ~original; return ~(invertedOriginal | NamesToMask(layerNames)); } + /// + /// Converts a LayerMask to an array of layer names. + /// + /// The LayerMask to convert. + /// An array of layer names included in the LayerMask. public static string[] MaskToNames(this LayerMask original) { List output = new List(); @@ -77,21 +119,44 @@ public static string[] MaskToNames(this LayerMask original) return output.ToArray(); } + /// + /// Converts a LayerMask to a string representation using a default delimiter. + /// + /// The LayerMask to convert. + /// A string representation of the LayerMask. public static string MaskToString(this LayerMask original) { return MaskToString(original, ", "); } + /// + /// Converts a LayerMask to a string representation using a specified delimiter. + /// + /// The LayerMask to convert. + /// The delimiter to use between layer names. + /// A string representation of the LayerMask. public static string MaskToString(this LayerMask original, string delimiter) { return string.Join(delimiter, MaskToNames(original)); } + /// + /// Moves the GameObject associated with the given Transform to a specified layer, optionally applying the change recursively to all children. + /// + /// The root Transform whose GameObject is to be moved to a new layer. + /// The name of the layer to move the GameObject to. + /// Whether to apply the layer change to all child Transforms recursively. public static void MoveToLayer(this Transform root, string layer, bool recursive = true) { MoveToLayer(root, LayerMask.NameToLayer(layer), recursive); } + /// + /// Moves the GameObject associated with the given Transform to a specified layer, optionally applying the change recursively to all children. + /// + /// The root Transform whose GameObject is to be moved to a new layer. + /// The layer number to move the GameObject to. + /// Whether to apply the layer change to all child Transforms recursively. public static void MoveToLayer(this Transform root, int layer, bool recursive = true) { root.gameObject.layer = layer; @@ -104,12 +169,24 @@ public static void MoveToLayer(this Transform root, int layer, bool recursive = } } } - + + /// + /// Moves all GameObjects associated with the given Transform and its children of type T to a specified layer. + /// + /// The component type to filter the children by. + /// The root Transform whose children are to be moved to a new layer. + /// The name of the layer to move the GameObjects to. public static void MoveToLayer(this Transform root, string layer) where T : Component { MoveToLayer(root, LayerMask.NameToLayer(layer)); } - + + /// + /// Moves all GameObjects associated with the given Transform and its children of type T to a specified layer. + /// + /// The component type to filter the children by. + /// The root Transform whose children are to be moved to a new layer. + /// The layer number to move the GameObjects to. public static void MoveToLayer(this Transform root, int layerNumber) where T : Component { foreach (T trans in root.GetComponentsInChildren(true)) @@ -118,11 +195,22 @@ public static void MoveToLayer(this Transform root, int layerNumber) where T } } + /// + /// Checks if a LayerMask contains a specific layer number. + /// + /// The LayerMask to check. + /// The layer number to check for. + /// True if the LayerMask contains the layer, false otherwise. public static bool ContainsLayer(this LayerMask mask, int layer) { return ((1 << layer) & mask) > 0; } + /// + /// Checks if a LayerMask contains a specific layer by name. + /// + /// The LayerMask to check. + /// The name of the layer to check for. public static bool ContainsLayer(this LayerMask mask, string layer) { return ((1 << LayerMask.NameToLayer(layer)) & mask) > 0; diff --git a/Packages/Unity_Extensions/Scripts/MiscExtensions.cs b/Packages/Unity_Extensions/Scripts/MiscExtensions.cs index 42bf129..af7669d 100644 --- a/Packages/Unity_Extensions/Scripts/MiscExtensions.cs +++ b/Packages/Unity_Extensions/Scripts/MiscExtensions.cs @@ -11,10 +11,10 @@ namespace GG.Extensions { - public static class MiscExtensions + public static class MiscExtensions { public delegate void UnityAction(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4); - + /// /// An actual quit that will stop play mode in editor as well /// @@ -26,7 +26,7 @@ public static void Quit() Application.Quit(); #endif } - + /// /// Ensure the resources directory lives at 'Assets' level /// @@ -39,16 +39,20 @@ public static void EnsureResourcesExists() Directory.CreateDirectory(path); } } - - /// Use this method to get all loaded objects of some type, including inactive objects. - /// This is an alternative to Resources.FindObjectsOfTypeAll (returns project assets, including prefabs), and GameObject.FindObjectsOfTypeAll (deprecated). + + /// + /// Finds all objects of type T in all loaded scenes, including inactive objects. + /// This method is an alternative to Resources.FindObjectsOfTypeAll (which returns project assets, including prefabs), + /// and GameObject.FindObjectsOfTypeAll (which is deprecated). + /// + /// The type of the objects to find. + /// A list of objects of type T found in all loaded scenes. public static List FindObjectsOfTypeAll() { List results = new List(); for (int i = 0; i < SceneManager.sceneCount; i++) { var s = SceneManager.GetSceneAt(i); - results.AddRange(FindObjectsOfTypeAllInScene(s, false)); } @@ -56,59 +60,70 @@ public static List FindObjectsOfTypeAll() { results.AddRange(savedObject.GetComponentsInChildren(true)); } - + return results; } - - public static List FindObjectsOfTypeAllInScene(Scene scene, bool includeDontDestroyOnLoad = true) - { - List results = new List(); - - var allGameObjects = scene.GetRootGameObjects(); - for (int j = 0; j < allGameObjects.Length; j++) - { - var go = allGameObjects[j]; - results.AddRange(go.GetComponentsInChildren(true)); - } - - if (includeDontDestroyOnLoad) + + /// + /// Finds all objects of type T in a specific scene, including inactive objects. + /// Optionally includes objects marked as DontDestroyOnLoad. + /// + /// The type of the objects to find. + /// The scene to search within. + /// Whether to include objects marked as DontDestroyOnLoad. + /// A list of objects of type T found in the specified scene. + public static List FindObjectsOfTypeAllInScene(Scene scene, bool includeDontDestroyOnLoad = true) { - foreach (GameObject savedObject in GameObjectExtensions.GetDontDestroyOnLoadObjects()) + List results = new List(); + + var allGameObjects = scene.GetRootGameObjects(); + for (int j = 0; j < allGameObjects.Length; j++) { - results.AddRange(savedObject.GetComponentsInChildren(true)); + var go = allGameObjects[j]; + results.AddRange(go.GetComponentsInChildren(true)); } - } - return results; - } + if (includeDontDestroyOnLoad) + { + foreach (GameObject savedObject in GameObjectExtensions.GetDontDestroyOnLoadObjects()) + { + results.AddRange(savedObject.GetComponentsInChildren(true)); + } + } - public static IEnumerator WaitForSceneToLoad(string sceneName, LoadSceneMode loadSceneMode, UnityAction updateAction, UnityAction OnComplete) + return results; + } + + /// + /// Asynchronously loads a scene by name and provides progress updates and a completion callback. + /// + /// The name of the scene to load. + /// Specifies whether to load the scene additively or replace the current scene. + /// An action to perform with the loading progress (0.0 to 0.9). + /// An action to perform once the scene is fully loaded and activated. + /// An IEnumerator for coroutine support, allowing this method to yield until the scene has loaded. + public static IEnumerator WaitForSceneToLoad(string sceneName, LoadSceneMode loadSceneMode, + UnityAction updateAction, UnityAction OnComplete) { AsyncOperation async = SceneManager.LoadSceneAsync(sceneName, loadSceneMode); async.allowSceneActivation = false; while (async.progress < 0.9f) { - if (updateAction != null) - { - updateAction(async.progress); - } + updateAction?.Invoke(async.progress); yield return null; } async.allowSceneActivation = true; - while (SceneManager.GetSceneByName(sceneName).isLoaded == false) + while (!SceneManager.GetSceneByName(sceneName).isLoaded) { yield return new WaitForSeconds(0.1f); } - if (OnComplete != null) - { - OnComplete(); - } + OnComplete?.Invoke(); } - + /// /// Clone data from an object into a new version of it /// @@ -117,7 +132,7 @@ public static IEnumerator WaitForSceneToLoad(string sceneName, LoadSceneMode loa /// public static T Clone(T obj) { - DataContractSerializer dcSer = new DataContractSerializer(obj.GetType()); + DataContractSerializer dcSer = new DataContractSerializer(obj.GetType()); MemoryStream memoryStream = new MemoryStream(); dcSer.WriteObject(memoryStream, obj); @@ -136,16 +151,27 @@ public static T Clone(T obj) /// /// /// - public static void CopyAll(this T source, T2 target) + public static void CopyAll(this T source, T2 target) { Type type = typeof(T); foreach (FieldInfo sourceField in type.GetFields()) { FieldInfo targetField = type.GetField(sourceField.Name); targetField.SetValue(target, sourceField.GetValue(source)); - } + } } - + + /// + /// Calculates the number of columns and rows in a vertical grid layout based on the active children. + /// + /// The GridLayoutGroup for which to calculate columns and rows. + /// The number of columns in the grid. Output parameter. + /// The number of rows in the grid. Output parameter. + /// + /// This method assumes that the grid starts with at least one column and one row. + /// It iterates through all child objects of the GridLayoutGroup, counting the number of columns and rows + /// based on the positions of the child objects. It only considers active child objects. + /// public static void GetColumnAndRowForVerticalGrid(this GridLayoutGroup glg, out int column, out int row) { column = 0; @@ -170,7 +196,7 @@ public static void GetColumnAndRowForVerticalGrid(this GridLayoutGroup glg, out { continue; } - + //Get the next child RectTransform currentChildObj = glg.transform.GetChild(i).GetComponent(); @@ -188,24 +214,29 @@ public static void GetColumnAndRowForVerticalGrid(this GridLayoutGroup glg, out } } } - + /// - /// warpper for index of comming from an array + /// Finds the index of the first occurrence of an object in an array. /// - /// - /// - /// - /// + /// The array to search. + /// The object to find the index of. + /// The type of the objects in the array. + /// The index of the first occurrence of the object in the array; -1 if not found. public static int IndexOf(this T[] array, T obj) { return Array.IndexOf(array, obj); } - + + /// + /// Trims the milliseconds from a DateTime object, returning a new DateTime object. + /// + /// The DateTime object to trim milliseconds from. + /// A new DateTime object with the milliseconds set to 0. public static DateTime TrimMilliseconds(this DateTime dt) { return new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, 0, dt.Kind); } - + /// /// Wait a set number of frames in a coroutine /// @@ -220,7 +251,7 @@ public static IEnumerator Frames(int frameCount) yield return frame; } } - + /// /// Creates a runtime sprite from a texture2D /// @@ -233,5 +264,4 @@ public static Sprite CreateSprite(this Texture2D t) return s; } } -} - +} \ No newline at end of file diff --git a/Packages/Unity_Extensions/Scripts/NumberExtensions.cs b/Packages/Unity_Extensions/Scripts/NumberExtensions.cs index 0648ea3..929462b 100644 --- a/Packages/Unity_Extensions/Scripts/NumberExtensions.cs +++ b/Packages/Unity_Extensions/Scripts/NumberExtensions.cs @@ -3,20 +3,49 @@ namespace GG.Extensions { + /// + /// Provides extension methods for numeric types to perform various rounding operations and checks. + /// public static class NumberExtensions { + /// + /// Defines the rounding mode to be used. + /// public enum RoundMode { + /// + /// Round to the nearest multiple. + /// UpDown, + /// + /// Always round up to the nearest multiple. + /// Up, + /// + /// Always round down to the nearest multiple. + /// Down } + /// + /// Rounds an integer to the nearest multiple of a specified number, with an optional rounding mode. + /// + /// The integer to round. + /// The multiple to round to. + /// The rounding mode to use. Defaults to UpDown. + /// The rounded integer. public static int NearestMultipleOf(this int x, int multiple, RoundMode rm = RoundMode.UpDown) { return Mathf.RoundToInt(((float)x).NearestMultipleOf((float)multiple, rm)); } + /// + /// Rounds a float to the nearest multiple of a specified number, with an optional rounding mode. + /// + /// The float to round. + /// The multiple to round to. + /// The rounding mode to use. Defaults to UpDown. + /// The rounded float. public static float NearestMultipleOf(this float x, float multiple, RoundMode rm = RoundMode.UpDown) { float mod = x % multiple; @@ -37,26 +66,33 @@ public static float NearestMultipleOf(this float x, float multiple, RoundMode rm { return x + (multiple - mod); } - else//(rm == RoundMode.Down) + else // (rm == RoundMode.Down) { return x - mod; } } + /// + /// Checks if a float value falls within a specified range, inclusive of the range boundaries. + /// + /// The float value to check. + /// The lower boundary of the range. + /// The upper boundary of the range. + /// True if the value falls within the range, false otherwise. public static bool FallsBetween(this float numberToCheck, float bottom, float top) { return (numberToCheck >= bottom && numberToCheck <= top); } - + /// - /// Round a float to X decimal places + /// Rounds a float value to a specified number of decimal places. /// - /// - /// - /// + /// The float value to round. + /// The number of decimal places to round to. + /// The rounded float value. public static float Round(this float value, int digits) { return (float)Math.Round(value, digits); } } -} +} \ No newline at end of file diff --git a/Packages/Unity_Extensions/Scripts/RectTramsformExtensions.cs b/Packages/Unity_Extensions/Scripts/RectTramsformExtensions.cs index 5ef2884..aaff3a2 100644 --- a/Packages/Unity_Extensions/Scripts/RectTramsformExtensions.cs +++ b/Packages/Unity_Extensions/Scripts/RectTramsformExtensions.cs @@ -2,6 +2,9 @@ namespace GG.Extensions { + /// + /// Defines preset anchor positions for RectTransforms. + /// public enum AnchorPresets { TopLeft, @@ -27,7 +30,9 @@ public enum AnchorPresets StretchAll } - + /// + /// Defines preset pivot positions for RectTransforms. + /// public enum PivotPresets { TopLeft, @@ -45,6 +50,13 @@ public enum PivotPresets public static class RectTransformExtensions { + /// + /// Sets the anchor of a RectTransform to a predefined preset. + /// + /// The RectTransform to modify. + /// The AnchorPresets value to apply. + /// Optional X offset from the anchor position. + /// Optional Y offset from the anchor position. public static void SetAnchor(this RectTransform source, AnchorPresets allign, int offsetX=0, int offsetY=0) { source.anchoredPosition = new Vector3(offsetX, offsetY, 0); @@ -154,7 +166,12 @@ public static void SetAnchor(this RectTransform source, AnchorPresets allign, in } } } - + + /// + /// Sets the pivot of a RectTransform to a predefined preset. + /// + /// The RectTransform to modify. + /// The PivotPresets value to apply. public static void SetPivot(this RectTransform source, PivotPresets preset) { diff --git a/Packages/Unity_Extensions/Scripts/RendererExtensions.cs b/Packages/Unity_Extensions/Scripts/RendererExtensions.cs index d4ebbae..bf2033a 100644 --- a/Packages/Unity_Extensions/Scripts/RendererExtensions.cs +++ b/Packages/Unity_Extensions/Scripts/RendererExtensions.cs @@ -2,8 +2,22 @@ namespace GG.Extensions { + /// + /// Provides extension methods for the Renderer component. + /// public static class RendererExtensions { + /// + /// Sets a specific material to a renderer at the given index. + /// + /// The renderer to modify. + /// The index at which to set the material. + /// The new material to set. + /// + /// This method modifies the materials array of the renderer. It first copies the current materials into a new array, + /// replaces the material at the specified index, and then sets the modified array back to the renderer. + /// This is useful for dynamically changing materials of game objects at runtime. + /// public static void SetMaterial(this Renderer renderer, int index, Material material) { Material[] mats = renderer.materials; diff --git a/Packages/Unity_Extensions/Scripts/SecurityExtensions.cs b/Packages/Unity_Extensions/Scripts/SecurityExtensions.cs index cb19e83..4582a8d 100644 --- a/Packages/Unity_Extensions/Scripts/SecurityExtensions.cs +++ b/Packages/Unity_Extensions/Scripts/SecurityExtensions.cs @@ -131,83 +131,102 @@ public static bool PasswordHashCompare(this string password, string original) #region Salt Key Encryption - public static List SaltKeyEncrypt(string data, string salt) - { - byte[] key = Encoding.UTF8.GetBytes(salt); - using (HMACSHA512 sha512 = new HMACSHA512(key)) - { - byte[] payload = Encoding.UTF8.GetBytes(data); - byte[] binaryHash = sha512.ComputeHash(payload); - string stringHash = Convert.ToBase64String(binaryHash); - - List l = new List - { - Convert.ToBase64String(payload), - stringHash - }; +/// +/// Encrypts the given data using HMAC SHA512 hashing with a specified salt key. +/// +/// The data to encrypt. +/// The salt key to use for encryption. +/// A list containing the base64 encoded payload and its HMAC SHA512 hash. +public static List SaltKeyEncrypt(string data, string salt) +{ + byte[] key = Encoding.UTF8.GetBytes(salt); + using (HMACSHA512 sha512 = new HMACSHA512(key)) + { + byte[] payload = Encoding.UTF8.GetBytes(data); + byte[] binaryHash = sha512.ComputeHash(payload); + string stringHash = Convert.ToBase64String(binaryHash); - return l; - } - } - - public static string SaltKeyDecrypt(string[] data, string salt) + List l = new List { - string hash = data[1]; - byte[] key = Encoding.UTF8.GetBytes(salt); - using (HMACSHA512 sha512 = new HMACSHA512(key)) - { - byte[] payload = Convert.FromBase64String(data[0]); - byte[] binaryHash = sha512.ComputeHash(payload); - string stringHash = Convert.ToBase64String(binaryHash); + Convert.ToBase64String(payload), + stringHash + }; - if (hash == stringHash) - { - string d = Encoding.UTF8.GetString(payload); - return d; - } - } + return l; + } +} + +/// +/// Decrypts the given data using HMAC SHA512 hashing with a specified salt key, comparing it against a known hash. +/// +/// An array where the first element is the base64 encoded payload and the second element is its hash. +/// The salt key used during encryption. +/// The decrypted data if the hash matches, otherwise an empty string. +public static string SaltKeyDecrypt(string[] data, string salt) +{ + string hash = data[1]; + byte[] key = Encoding.UTF8.GetBytes(salt); + using (HMACSHA512 sha512 = new HMACSHA512(key)) + { + byte[] payload = Convert.FromBase64String(data[0]); + byte[] binaryHash = sha512.ComputeHash(payload); + string stringHash = Convert.ToBase64String(binaryHash); - return ""; + if (hash == stringHash) + { + string d = Encoding.UTF8.GetString(payload); + return d; } + } + + return ""; +} #endregion #region AES - public static string AesEncryption(string rawValue, string key, string iv) + /// +/// Encrypts a given string using AES encryption with a specified key and initialization vector (IV). +/// +/// The string to encrypt. +/// The encryption key as a string. It will be converted to bytes internally. +/// The initialization vector as a string. It will be converted to bytes internally. +/// The encrypted string, converted from bytes to a string representation. +public static string AesEncryption(string rawValue, string key, string iv) +{ + byte[] keyByte = StringToBytes(key); // Convert the key from string to bytes + byte[] ivByte = StringToBytes(iv); // Convert the IV from string to bytes + + byte[] encrypted; // To hold the encrypted data bytes + string s = string.Empty; // Initialize an empty string to hold the final encrypted string + using (Aes aesAlg = Aes.Create()) // Create a new instance of the Aes class + { + aesAlg.Key = keyByte; // Set the encryption key + aesAlg.IV = ivByte; // Set the initialization vector + + // Create an encryptor to perform the stream transform. + ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); + + // Create the streams used for encryption. + using (MemoryStream msEncrypt = new MemoryStream()) { - byte[] keyByte = StringToBytes(key); - byte[] ivByte = StringToBytes(iv); - - byte[] encrypted; - string s = string.Empty; - using (Aes aesAlg = Aes.Create()) + using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { - aesAlg.Key = keyByte; - aesAlg.IV = ivByte; - - // Create an encryptor to perform the stream transform. - ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); - - // Create the streams used for encryption. - using (MemoryStream msEncrypt = new MemoryStream()) + using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { - using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) - { - using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) - { - //Write all data to the stream. - swEncrypt.Write(rawValue); - } + //Write all data to the stream. + swEncrypt.Write(rawValue); + } - encrypted = msEncrypt.ToArray(); + encrypted = msEncrypt.ToArray(); // Convert the encrypted data stream to a byte array - s = BytesToString(encrypted); - } - } + s = BytesToString(encrypted); // Convert the encrypted bytes to a string } - - return s; } + } + + return s; // Return the encrypted string +} /// /// Decrypt the byte array into a ascii readable string diff --git a/Packages/Unity_Extensions/Scripts/StringExtensions.cs b/Packages/Unity_Extensions/Scripts/StringExtensions.cs index a60f8b7..42c11bc 100644 --- a/Packages/Unity_Extensions/Scripts/StringExtensions.cs +++ b/Packages/Unity_Extensions/Scripts/StringExtensions.cs @@ -47,10 +47,12 @@ public static string ExtractInitialsFromName(string name) initials = Regex.Replace(initials, @"\p{Z}+", " "); // Remove all Sr, Jr, I, II, III, IV, V, VI, VII, VIII, IX at the end of names - initials = Regex.Replace(initials.Trim(), @"\s+(?:[JS]R|I{1,3}|I[VX]|VI{0,3})$", "", RegexOptions.IgnoreCase); + initials = Regex.Replace(initials.Trim(), @"\s+(?:[JS]R|I{1,3}|I[VX]|VI{0,3})$", "", + RegexOptions.IgnoreCase); // Extract up to 2 initials from the remaining cleaned name. - initials = Regex.Replace(initials, @"^(\p{L})[^\s]*(?:\s+(?:\p{L}+\s+(?=\p{L}))?(?:(\p{L})\p{L}*)?)?$", "$1$2").Trim(); + initials = Regex.Replace(initials, @"^(\p{L})[^\s]*(?:\s+(?:\p{L}+\s+(?=\p{L}))?(?:(\p{L})\p{L}*)?)?$", + "$1$2").Trim(); if (initials.Length > 2) { @@ -61,48 +63,73 @@ public static string ExtractInitialsFromName(string name) return initials.ToUpperInvariant(); } + /// + /// Extracts the first name and the initial of the last name from a full name. + /// + /// The full name from which to extract the first name and initial. + /// A string containing the first name and the initial of the last name. public static string FirstNameAndInitial(string name) { name = Regex.Match(name, @"[A-Za-z]+\s+[A-Za-z]").Value; return name; } + /// - /// Use the current thread's culture info for conversion + /// Converts a string to title case using the current thread's culture info. /// + /// The string to convert to title case. + /// The converted string in title case. public static string TitleCase(this string str) { CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture; return cultureInfo.TextInfo.ToTitleCase(str.ToLower()); } - + /// - /// Overload which uses the culture info with the specified name + /// Converts a string to title case using a specified culture info by name. /// + /// The string to convert to title case. + /// The name of the culture info to use for conversion. + /// The converted string in title case. public static string TitleCase(this string str, string cultureInfoName) { CultureInfo cultureInfo = new CultureInfo(cultureInfoName); return cultureInfo.TextInfo.ToTitleCase(str.ToLower()); } - + /// - /// Overload which uses the specified culture info + /// Converts a string to title case using a specified culture info. /// + /// The string to convert to title case. + /// The culture info to use for conversion. + /// The converted string in title case. public static string TitleCase(this string str, CultureInfo cultureInfo) { return cultureInfo.TextInfo.ToTitleCase(str.ToLower()); } - - + + /// + /// Splits a string at specified indices. + /// + /// The source string to split. + /// An array of indices where the string should be split. + /// An array of substrings created by splitting the source string. public static string[] SplitAtIndexs(this string source, params int[] index) { - var indices = new[] {0}.Union(index).Union(new[] {source.Length}); + var indices = new[] { 0 }.Union(index).Union(new[] { source.Length }); return indices .Zip(indices.Skip(1), (a, b) => (a, b)) .Select(_ => source.Substring(_.a, _.b - _.a)).ToArray(); } + /// + /// Splits a string into two parts at the nearest space to the middle, ensuring that neither part exceeds a specified maximum length. + /// + /// The source string to split. + /// The maximum length of each part after splitting. + /// The source string split into two parts, if necessary, at the nearest space to the middle. public static string SliceString(this string source, int maxCharacterLengthInLine) { if (source.Length >= maxCharacterLengthInLine) @@ -132,4 +159,4 @@ public static string SliceString(this string source, int maxCharacterLengthInLin return source; } } -} +} \ No newline at end of file diff --git a/Packages/Unity_Extensions/Scripts/XR/LayerMaskExtensions.cs b/Packages/Unity_Extensions/Scripts/XR/LayerMaskExtensions.cs index 71008dc..c12ee58 100644 --- a/Packages/Unity_Extensions/Scripts/XR/LayerMaskExtensions.cs +++ b/Packages/Unity_Extensions/Scripts/XR/LayerMaskExtensions.cs @@ -7,16 +7,31 @@ namespace GG.Extensions.Vr { public static class InteractionLayerMaskExtensions { + /// + /// Creates a layer mask from the specified layer names. + /// + /// The layer names to include in the mask. + /// An InteractionLayerMask representing the specified layers. public static InteractionLayerMask CreateLayerMask(params string[] layerNames) { return NamesToMask(layerNames); } + /// + /// Creates a layer mask from the specified layer numbers. + /// + /// The layer numbers to include in the mask. + /// An InteractionLayerMask representing the specified layers. public static InteractionLayerMask CreateLayerMask(params int[] layerNumbers) { return LayerNumbersToMask(layerNumbers); } + /// + /// Converts an array of layer names into an InteractionLayerMask. + /// + /// The layer names to convert. + /// An InteractionLayerMask representing the specified layers. public static InteractionLayerMask NamesToMask(params string[] layerNames) { InteractionLayerMask ret = 0; @@ -28,6 +43,11 @@ public static InteractionLayerMask NamesToMask(params string[] layerNames) return ret; } + /// + /// Converts an array of layer numbers into an InteractionLayerMask. + /// + /// The layer numbers to convert. + /// An InteractionLayerMask representing the specified layers. public static InteractionLayerMask LayerNumbersToMask(params int[] layerNumbers) { InteractionLayerMask ret = 0; @@ -39,22 +59,45 @@ public static InteractionLayerMask LayerNumbersToMask(params int[] layerNumbers) return ret; } + /// + /// Inverts the specified InteractionLayerMask. + /// + /// The original InteractionLayerMask to invert. + /// An inverted InteractionLayerMask. public static InteractionLayerMask Inverse(this InteractionLayerMask original) { return ~original; } + /// + /// Adds layers to the specified InteractionLayerMask. + /// + /// The original InteractionLayerMask. + /// The layer names to add. + /// An InteractionLayerMask with the specified layers added. public static InteractionLayerMask AddToMask(this InteractionLayerMask original, params string[] layerNames) { return original | NamesToMask(layerNames); } - public static InteractionLayerMask RemoveFromMask(this InteractionLayerMask original, params string[] layerNames) + /// + /// Removes layers from the specified InteractionLayerMask. + /// + /// The original InteractionLayerMask. + /// The layer names to remove. + /// An InteractionLayerMask with the specified layers removed. + public static InteractionLayerMask RemoveFromMask(this InteractionLayerMask original, + params string[] layerNames) { InteractionLayerMask invertedOriginal = ~original; return ~(invertedOriginal | NamesToMask(layerNames)); } + /// + /// Converts an InteractionLayerMask to an array of layer names. + /// + /// The InteractionLayerMask to convert. + /// An array of layer names represented by the InteractionLayerMask. public static string[] MaskToNames(this InteractionLayerMask original) { List output = new List(); @@ -75,21 +118,44 @@ public static string[] MaskToNames(this InteractionLayerMask original) return output.ToArray(); } - public static string MaskToString(this InteractionLayerMask original) + /// + /// Converts an InteractionLayerMask to a string representation, using a specified delimiter. + /// + /// The InteractionLayerMask to convert. + /// The delimiter to use between layer names. + /// A string representation of the InteractionLayerMask. + public static string MaskToString(this InteractionLayerMask original, string delimiter) { - return MaskToString(original, ", "); + return string.Join(delimiter, MaskToNames(original)); } - public static string MaskToString(this InteractionLayerMask original, string delimiter) + /// + /// Converts an InteractionLayerMask to a string representation with a default delimiter. + /// + /// The InteractionLayerMask to convert. + /// A string representation of the InteractionLayerMask, separated by ", ". + public static string MaskToString(this InteractionLayerMask original) { - return string.Join(delimiter, MaskToNames(original)); + return MaskToString(original, ", "); } + /// + /// Moves the GameObject associated with the specified Transform to a new layer, optionally applying the change recursively to all children. + /// + /// The root Transform whose GameObject's layer will be changed. + /// The name of the layer to move the GameObject to. + /// Whether to apply the layer change to all child GameObjects recursively. public static void MoveToLayer(this Transform root, string layer, bool recursive = true) { MoveToLayer(root, InteractionLayerMask.NameToLayer(layer), recursive); } + /// + /// Moves the GameObject associated with the specified Transform to a new layer, optionally applying the change recursively to all children. + /// + /// The root Transform whose GameObject's layer will be changed. + /// The layer number to move the GameObject to. + /// Whether to apply the layer change to all child GameObjects recursively. public static void MoveToLayer(this Transform root, int layer, bool recursive = true) { root.gameObject.layer = layer; @@ -102,12 +168,24 @@ public static void MoveToLayer(this Transform root, int layer, bool recursive = } } } - + + /// + /// Moves all GameObjects of a specific component type within the children of the specified Transform to a new layer. + /// + /// The component type to filter the GameObjects by. + /// The root Transform to search within. + /// The name of the layer to move the GameObjects to. public static void MoveToLayer(this Transform root, string layer) where T : Component { MoveToLayer(root, InteractionLayerMask.NameToLayer(layer)); } - + + /// + /// Moves all GameObjects of a specific component type within the children of the specified Transform to a new layer. + /// + /// The component type to filter the GameObjects by. + /// The root Transform to search within. + /// The layer number to move the GameObjects to. public static void MoveToLayer(this Transform root, int layerNumber) where T : Component { foreach (T trans in root.GetComponentsInChildren(true)) @@ -116,11 +194,23 @@ public static void MoveToLayer(this Transform root, int layerNumber) where T } } + /// + /// Checks if the specified InteractionLayerMask contains a specific layer number. + /// + /// The InteractionLayerMask to check. + /// The layer number to check for. + /// True if the mask contains the layer, otherwise false. public static bool ContainsLayer(this InteractionLayerMask mask, int layer) { return ((1 << layer) & mask) > 0; } + /// + /// Checks if the specified InteractionLayerMask contains a specific layer name. + /// + /// The InteractionLayerMask to check. + /// The name of the layer to check for. + /// True if the mask contains the layer, otherwise false. public static bool ContainsLayer(this InteractionLayerMask mask, string layer) { return ((1 << InteractionLayerMask.NameToLayer(layer)) & mask) > 0; diff --git a/Packages/Unity_Extensions/Scripts/XR/XrExtensions.cs b/Packages/Unity_Extensions/Scripts/XR/XrExtensions.cs index b7ad7bd..ae25fbb 100644 --- a/Packages/Unity_Extensions/Scripts/XR/XrExtensions.cs +++ b/Packages/Unity_Extensions/Scripts/XR/XrExtensions.cs @@ -4,19 +4,32 @@ namespace GG.Extensions.Vr { + /// + /// Provides extension methods for XR (Extended Reality) functionalities. + /// public static class XrExtensions { + /// + /// Checks if an XR headset is currently present and running. + /// + /// True if an XR headset is present and running; otherwise, false. public static bool IsHeadsetPresent() { + // Create a list to hold XR display subsystems List xrDisplaySubsystems = new List(); + // Populate the list with the current XR display subsystem instances SubsystemManager.GetInstances(xrDisplaySubsystems); + // Iterate through each XR display subsystem foreach (XRDisplaySubsystem xrDisplay in xrDisplaySubsystems) { + // Check if the XR display subsystem is running if (xrDisplay.running) { + // If running, return true indicating a headset is present return true; } } + // If no running XR display subsystem is found, return false return false; } }