Skip to content

Instantly share code, notes, and snippets.

@jbvrtx
Last active June 12, 2023 14:32
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 jbvrtx/29c6cd817c8eabe6e4d0b8ac4d8d89c8 to your computer and use it in GitHub Desktop.
Save jbvrtx/29c6cd817c8eabe6e4d0b8ac4d8d89c8 to your computer and use it in GitHub Desktop.
Extensions for Scripting with Unity Editor
public static class Extensions
{
public static void RemoveComponent<T>(this GameObject gameObject) where T : UnityEngine.Component
{
GameObject.Destroy(gameObject.GetComponent<T>());
}
public static void ExecuteNextFrame(this MonoBehaviour monoBehaviour, DelayedFunction delayedFunction)
{
if (delayedFunction != null)
monoBehaviour.StartCoroutine(CoroutineExecuteNextFrame(delayedFunction));
}
private static IEnumerator CoroutineExecuteNextFrame(DelayedFunction delayedFunction)
{
yield return new WaitForFixedUpdate();
delayedFunction();
}
public static void ExecuteAfterDelay(this MonoBehaviour monoBehaviour, DelayedFunction delayedFunction,
float delaySeconds)
{
if (delayedFunction != null)
monoBehaviour.StartCoroutine(CoroutineAfterDelay(delayedFunction, delaySeconds));
}
private static IEnumerator CoroutineAfterDelay(DelayedFunction delayedFunction, float delay)
{
yield return new WaitForSeconds(delay);
delayedFunction();
}
/// <summary>
/// Usage: EventSystem.current.IsPointerOverUIObject()
/// </summary>
public static bool IsPointerOverUIObject(this EventSystem system)
{
if (!EventSystem.current) return false;
// Should get the average position of all current touches on iOS
PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
eventDataCurrentPosition.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
// Raycast against UI elements
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
return results.Count > 0;
}
public static float? ParseFloat(this string floatString)
{
if (String.IsNullOrWhiteSpace(floatString)) return null;
if (float.TryParse(floatString, NumberStyles.Float, CultureInfo.InvariantCulture, out float f))
return f;
return 0;
}
/// <summary>
/// Example:
/// UnityWebRequest getRequest = UnityWebRequest.Get("http://www.google.com");
/// await getRequest.SendWebRequest();
/// var result = getRequest.downloadHandler.text;
/// </summary>
/// <param name="asyncOp"></param>
/// <returns></returns>
public static TaskAwaiter GetAwaiter(this AsyncOperation asyncOp)
{
var tcs = new TaskCompletionSource<object>();
asyncOp.completed += obj => { tcs.SetResult(null); };
return ((Task)tcs.Task).GetAwaiter();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment