Extension methods to create simple code around working with WeakReferences referencing UnityEngine.Objects.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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