Skip to content

Instantly share code, notes, and snippets.

@FlaShG
Created July 25, 2019 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FlaShG/7581ae43ad093f54f78a33f946d11d60 to your computer and use it in GitHub Desktop.
Save FlaShG/7581ae43ad093f54f78a33f946d11d60 to your computer and use it in GitHub Desktop.
Extension methods to create simple code around working with WeakReferences referencing UnityEngine.Objects.
using UnityEngine;
/// <summary>
/// Extension methods to create simple code around working with WeakReferences referencing UnityEngine.Objects.
/// </summary>
public static class WeakReferenceExtensions
{
/// <summary>
/// Destroys the referenced object if it still exists.
/// Does nothing if no object is referenced or the referenced object is already destroyed.
/// </summary>
/// <param name="obj">The object to destroy.</param>
public static void Destroy<T>(this System.WeakReference<T> obj) where T : Object
{
if (obj != null && obj.TryGetTarget(out var target) && Exists(target))
{
Object.Destroy(target);
}
}
/// <summary>
/// Destroys the referenced component's GameObject if it still exists.
/// Does nothing if no component is referenced or the referenced component's GameObject is already destroyed.
/// </summary>
/// <param name="obj">The object to destroy.</param>
public static void DestroyGameObject<T>(this System.WeakReference<T> obj) where T : Component
{
if (obj != null && obj.TryGetTarget(out var target) && Exists(target) && Exists(target.gameObject))
{
Object.Destroy(target.gameObject);
}
}
/// <summary>
/// Checks whether an object is referenced, and whether that object isn't destroyed.
/// </summary>
/// <param name="obj">The object to check.</param>
/// <returns>True if a WeakReference is passed which references an object that is not destroyed.</returns>
public static bool Exists<T>(this System.WeakReference<T> obj) where T : Object
{
return obj != null && obj.TryGetTarget(out var target) && Exists(target);
}
private static bool Exists(Object obj)
{
return obj != null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment