Skip to content

Instantly share code, notes, and snippets.

@GhatSmith
Created September 11, 2018 22:29
Show Gist options
  • Save GhatSmith/79b348fc402c4e08662a5dde5f801ba9 to your computer and use it in GitHub Desktop.
Save GhatSmith/79b348fc402c4e08662a5dde5f801ba9 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
using System;
namespace OddTales.Framework.Core.ClassExtension
{
/// <summary>
/// Invoke methods of MonoBehaviour call other methods by name.
/// Methods called by name is hard to track in code (you cannot find "Usages")
/// It is easy to roll out your own Invoke using Coroutines
/// Code based on : http://www.gamasutra.com/blogs/HermanTulleken/20160812/279100/50_Tips_and_Best_Practices_for_Unity_2016_Edition.php
/// Warnings : slower than string Invoke + memory allocation (use GetEnumerator to cache Coroutine if you can)
/// </summary>
public static class InvokeExtension
{
/// <summary>
/// Example of use : this.Invoke(ShootEnemy); //where ShootEnemy is a parameterless void method.
/// You can also invoke methods with parameters : this.Invoke(() => AdditionMethod(5, 8), 4)
/// </summary>
public static Coroutine Invoke(this MonoBehaviour monoBehaviour, Action action, float time)
{
if (time.Equals(0)) return monoBehaviour.StartCoroutine(InvokeCoroutine(action, null));
else return monoBehaviour.StartCoroutine(InvokeCoroutine(action, new WaitForSeconds(time)));
}
/// <summary> You can cache WaitForSeconds in your code to reduce memory allocation </summary>
public static Coroutine Invoke(this MonoBehaviour monoBehaviour, Action action, WaitForSeconds time)
{
return monoBehaviour.StartCoroutine(InvokeCoroutine(action, time));
}
/// <summary> You can cache enumerator using GetEnumerator method to remove all memory allocation at Invoke time</summary>
public static Coroutine Invoke(this MonoBehaviour monoBehaviour, IEnumerator enumerator)
{
return monoBehaviour.StartCoroutine(enumerator);
}
/// <summary> Cache enumerator to avoid any memory allocation during Invoke </summary>
public static IEnumerator GetEnumerator(Action action, float time)
{
return time.Equals(0) ? GetEnumerator(action, null) : GetEnumerator(action, new WaitForSeconds(time));
}
/// <summary> Cache enumerator to avoid any memory allocation during Invoke </summary>
public static IEnumerator GetEnumerator(Action action, WaitForSeconds time)
{
return InvokeCoroutine(action, time);
}
private static IEnumerator InvokeCoroutine(Action action, WaitForSeconds time)
{
if (time != null) yield return time;
if (action != null) action.Invoke();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment