Skip to content

Commit

Permalink
Add Conversion Extension Methods
Browse files Browse the repository at this point in the history
  • Loading branch information
adammyhre committed Jun 21, 2024
1 parent 03a1859 commit b52c0ef
Show file tree
Hide file tree
Showing 13 changed files with 179 additions and 93 deletions.
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
## [1.0.1] - 2024-06-24
### Add Conversion Methods
- Added conversion methods between `UnityEngine` and `System.Numerics` vectors and quaternions.
- Adds missing namespaces to some classes

## [1.0.0]
### Initial Release and Additions
- Introduced foundational package contents.

### Added
- `AsyncOperation`, `Task`, and `Enumerable` extenstion methods.
- `RandomPointInAnnulus` with uniform distribution.
- `InRangeOf` with optional angle.

### Improved
- Optimized `GetWaitForSeconds`.

### Other Changes
- Added various extensions and helper methods for vectors, numbers, strings, layers, tasks, enumerables, and more.
- Included `FrameRateLimiter` helper and `LayerMask` extensions classes.
- Updated preprocessor directives and optimized helper methods.
7 changes: 7 additions & 0 deletions CHANGELOG.md.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Welcome to the Unity Utility Library, a growing collection of handy extension me
## Features

- **Extension Methods:** Extend Unity and C# built-in types with additional functionalities.
- **Conversion Extension Methods** Convert Vectors and Quaternions between System.Numerics and Unity.
- **Singletons:** Generic Singletons for various use cases.
- **Helpers:** Static helper methods such as NonAlloc WaitForSeconds.

Expand Down
22 changes: 12 additions & 10 deletions UnityUtils/Scripts/Extensions/AsyncOperationExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
using System.Threading.Tasks;
using UnityEngine;

public static class AsyncOperationExtensions {
/// <summary>
/// Extension method that converts an AsyncOperation into a Task.
/// </summary>
/// <param name="asyncOperation">The AsyncOperation to convert.</param>
/// <returns>A Task that represents the completion of the AsyncOperation.</returns>
public static Task AsTask(this AsyncOperation asyncOperation) {
var tcs = new TaskCompletionSource<bool>();
asyncOperation.completed += _ => tcs.SetResult(true);
return tcs.Task;
namespace UnityUtils {
public static class AsyncOperationExtensions {
/// <summary>
/// Extension method that converts an AsyncOperation into a Task.
/// </summary>
/// <param name="asyncOperation">The AsyncOperation to convert.</param>
/// <returns>A Task that represents the completion of the AsyncOperation.</returns>
public static Task AsTask(this AsyncOperation asyncOperation) {
var tcs = new TaskCompletionSource<bool>();
asyncOperation.completed += _ => tcs.SetResult(true);
return tcs.Task;
}
}
}
22 changes: 12 additions & 10 deletions UnityUtils/Scripts/Extensions/EnumerableExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
using System;
using System.Collections.Generic;

public static class EnumerableExtensions {
/// <summary>
/// Performs an action on each element in the sequence.
/// </summary>
/// <typeparam name="T">The type of elements in the sequence.</typeparam>
/// <param name="sequence">The sequence to iterate over.</param>
/// <param name="action">The action to perform on each element.</param>
public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action) {
foreach (var item in sequence) {
action(item);
namespace UnityUtils {
public static class EnumerableExtensions {
/// <summary>
/// Performs an action on each element in the sequence.
/// </summary>
/// <typeparam name="T">The type of elements in the sequence.</typeparam>
/// <param name="sequence">The sequence to iterate over.</param>
/// <param name="action">The action to perform on each element.</param>
public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action) {
foreach (var item in sequence) {
action(item);
}
}
}
}
20 changes: 11 additions & 9 deletions UnityUtils/Scripts/Extensions/LayerMaskExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
using UnityEngine;

public static class LayerMaskExtensions {
/// <summary>
/// Checks if the given layer number is contained in the LayerMask.
/// </summary>
/// <param name="mask">The LayerMask to check.</param>
/// <param name="layerNumber">The layer number to check if it is contained in the LayerMask.</param>
/// <returns>True if the layer number is contained in the LayerMask, otherwise false.</returns>
public static bool Contains(this LayerMask mask, int layerNumber) {
return mask == (mask | (1 << layerNumber));
namespace UnityUtils {
public static class LayerMaskExtensions {
/// <summary>
/// Checks if the given layer number is contained in the LayerMask.
/// </summary>
/// <param name="mask">The LayerMask to check.</param>
/// <param name="layerNumber">The layer number to check if it is contained in the LayerMask.</param>
/// <returns>True if the layer number is contained in the LayerMask, otherwise false.</returns>
public static bool Contains(this LayerMask mask, int layerNumber) {
return mask == (mask | (1 << layerNumber));
}
}
}
16 changes: 16 additions & 0 deletions UnityUtils/Scripts/Extensions/QuaternionConversionExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System.Runtime.CompilerServices;
using UnityEngine;

namespace UnityUtils {
public static class QuaternionConversionExtensions {
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Quaternion ToUnityQuaternion(this System.Numerics.Quaternion quaternion) {
return new Quaternion(quaternion.X, quaternion.Y, quaternion.Z, quaternion.W);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static System.Numerics.Quaternion ToSystemQuaternion(this Quaternion quaternion) {
return new System.Numerics.Quaternion(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

76 changes: 39 additions & 37 deletions UnityUtils/Scripts/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,45 +1,47 @@
using System;

public static class StringExtensions {
/// <summary>Checks if a string is Null or white space</summary>
public static bool IsNullOrWhiteSpace(this string val) => string.IsNullOrWhiteSpace(val);

/// <summary>Checks if a string is Null or empty</summary>
public static bool IsNullOrEmpty(this string value) => string.IsNullOrEmpty(value);

/// <summary>Checks if a string contains null, empty or white space.</summary>
public static bool IsBlank(this string val) => val.IsNullOrWhiteSpace() || val.IsNullOrEmpty();

/// <summary>Checks if a string is null and returns an empty string if it is.</summary>
public static string OrEmpty(this string val) => val ?? string.Empty;

/// <summary>
/// Shortens a string to the specified maximum length. If the string's length
/// is less than the maxLength, the original string is returned.
/// </summary>
public static string Shorten(this string val, int maxLength) {
if (val.IsBlank()) return val;
return val.Length <= maxLength ? val : val.Substring(0, maxLength);
}

/// <summary>Slices a string from the start index to the end index.</summary>
/// <result>The sliced string.</result>
public static string Slice(this string val, int startIndex, int endIndex) {
if (val.IsBlank()) {
throw new ArgumentNullException(nameof(val), "Value cannot be null or empty.");
namespace UnityUtils {
public static class StringExtensions {
/// <summary>Checks if a string is Null or white space</summary>
public static bool IsNullOrWhiteSpace(this string val) => string.IsNullOrWhiteSpace(val);

/// <summary>Checks if a string is Null or empty</summary>
public static bool IsNullOrEmpty(this string value) => string.IsNullOrEmpty(value);

/// <summary>Checks if a string contains null, empty or white space.</summary>
public static bool IsBlank(this string val) => val.IsNullOrWhiteSpace() || val.IsNullOrEmpty();

/// <summary>Checks if a string is null and returns an empty string if it is.</summary>
public static string OrEmpty(this string val) => val ?? string.Empty;

/// <summary>
/// Shortens a string to the specified maximum length. If the string's length
/// is less than the maxLength, the original string is returned.
/// </summary>
public static string Shorten(this string val, int maxLength) {
if (val.IsBlank()) return val;
return val.Length <= maxLength ? val : val.Substring(0, maxLength);
}

if (startIndex < 0 || startIndex > val.Length - 1) {
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
/// <summary>Slices a string from the start index to the end index.</summary>
/// <result>The sliced string.</result>
public static string Slice(this string val, int startIndex, int endIndex) {
if (val.IsBlank()) {
throw new ArgumentNullException(nameof(val), "Value cannot be null or empty.");
}

// If the end index is negative, it will be counted from the end of the string.
endIndex = endIndex < 0 ? val.Length + endIndex : endIndex;
if (startIndex < 0 || startIndex > val.Length - 1) {
throw new ArgumentOutOfRangeException(nameof(startIndex));
}

if (endIndex < 0 || endIndex < startIndex || endIndex > val.Length) {
throw new ArgumentOutOfRangeException(nameof(endIndex));
}
// If the end index is negative, it will be counted from the end of the string.
endIndex = endIndex < 0 ? val.Length + endIndex : endIndex;

if (endIndex < 0 || endIndex < startIndex || endIndex > val.Length) {
throw new ArgumentOutOfRangeException(nameof(endIndex));
}

return val.Substring(startIndex, endIndex - startIndex);
return val.Substring(startIndex, endIndex - startIndex);
}
}
}
}
52 changes: 27 additions & 25 deletions UnityUtils/Scripts/Extensions/TaskExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,35 @@
using System.Collections;
using System.Threading.Tasks;

public static class TaskExtensions {
/// <summary>
/// Converts the Task into an IEnumerator for Unity coroutine usage.
/// </summary>
/// <param name="task">The Task to convert.</param>
/// <returns>An IEnumerator representation of the Task.</returns>
public static IEnumerator AsCoroutine(this Task task) {
while (!task.IsCompleted) yield return null;
// When used on a faulted Task, GetResult() will propagate the original exception.
// see: https://devblogs.microsoft.com/pfxteam/task-exception-handling-in-net-4-5/
task.GetAwaiter().GetResult();
}

/// <summary>
/// Marks a task to be forgotten, meaning any exceptions thrown by the task will be caught and handled.
/// </summary>
/// <param name="task">The task to be forgotten.</param>
/// <param name="onException">The optional action to execute when an exception is caught. If provided, the exception will not be rethrown.</param>
public static async void Forget(this Task task, Action<Exception> onException = null) {
try {
await task;
namespace UnityUtils {
public static class TaskExtensions {
/// <summary>
/// Converts the Task into an IEnumerator for Unity coroutine usage.
/// </summary>
/// <param name="task">The Task to convert.</param>
/// <returns>An IEnumerator representation of the Task.</returns>
public static IEnumerator AsCoroutine(this Task task) {
while (!task.IsCompleted) yield return null;
// When used on a faulted Task, GetResult() will propagate the original exception.
// see: https://devblogs.microsoft.com/pfxteam/task-exception-handling-in-net-4-5/
task.GetAwaiter().GetResult();
}
catch (Exception exception) {
if (onException == null)
throw exception;

onException(exception);
/// <summary>
/// Marks a task to be forgotten, meaning any exceptions thrown by the task will be caught and handled.
/// </summary>
/// <param name="task">The task to be forgotten.</param>
/// <param name="onException">The optional action to execute when an exception is caught. If provided, the exception will not be rethrown.</param>
public static async void Forget(this Task task, Action<Exception> onException = null) {
try {
await task;
}
catch (Exception exception) {
if (onException == null)
throw exception;

onException(exception);
}
}
}
}
26 changes: 26 additions & 0 deletions UnityUtils/Scripts/Extensions/VectorConversionExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System.Runtime.CompilerServices;
using UnityEngine;

namespace UnityUtils {
public static class VectorConversionExtensions {
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 ToUnityVector(this System.Numerics.Vector2 vector) {
return new Vector2(vector.X, vector.Y);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static System.Numerics.Vector2 ToSystemVector(this Vector2 vector) {
return new System.Numerics.Vector2(vector.x, vector.y);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 ToUnityVector(this System.Numerics.Vector3 vector) {
return new Vector3(vector.X, vector.Y, vector.Z);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static System.Numerics.Vector3 ToSystemVector(this Vector3 vector) {
return new System.Numerics.Vector3(vector.x, vector.y, vector.z);
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "com.gitamend.unityutils",
"displayName": "Unity Utility Library",
"description": "Unity Utility Library, a growing collection of handy extension methods, helpers, attributes, and other utilities designed to enhance and simplify your Unity development workflow. Whether you're a seasoned developer or just starting, this library aims to provide tools that will help streamline your coding process and add efficiency to your projects.",
"version": "1.0.0",
"version": "1.0.1",
"keywords": [
"extension",
"attribute",
Expand All @@ -12,7 +12,7 @@
"category": "editor extensions",
"dependencies": {},
"author": {
"name": "Git-Amend",
"name": "Git Amend",
"url": "https://github.com/adammyhre"
},
"documentationUrl": "https://github.com/adammyhre/Unity-Utils/README.md"
Expand Down

0 comments on commit b52c0ef

Please sign in to comment.