Last active
December 25, 2015 07:49
-
-
Save fversnel/6942355 to your computer and use it in GitHub Desktop.
Creates an anonymous MonoBehaviour instance from a given update Action.
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
public static class AnonymousMonoBehaviours | |
{ | |
private static readonly Action EmptyAction = () => { }; | |
/// <summary> | |
/// Creates an anonymous MonoBehaviour instance from a given update Action. | |
/// The instance can be destroyed by calling Dispose on the returned IDisposable. | |
/// </summary> | |
/// <param name="updateFn">Called whenever AnonymousMonobehaviour.Update() is called.</param> | |
/// <param name="startFn">Called whenever AnonymousMonobehaviour.Start() is called.</param> | |
/// <param name="onDestroyFn">Called whenever AnonymousMonobehaviour.OnDestroy() is called, i.g. when disposable.Dispose() is called.</param> | |
/// <param name="name">The name of the game object that this AnonymousUpdateBehaviour will create</param> | |
/// <returns>A disposable allowing the caller to destroy this anonymous instance.</returns> | |
public static IDisposable Update(Action updateFn, Action startFn = null, Action onDestroyFn = null, string name = "AnonymousUpdateBehaviour") | |
{ | |
var g = GameObject.Instantiate(new GameObject()) as GameObject; | |
g.name = name; | |
var b = g.AddComponent<AnonymousUpdateBehaviour>(); | |
b.StartFn = startFn ?? EmptyAction; | |
b.UpdateFn = updateFn; | |
b.OnDestroyFn = onDestroyFn ?? EmptyAction; | |
return Disposable.Create(() => GameObject.Destroy(g)); | |
} | |
} | |
public class AnonymousUpdateBehaviour : MonoBehaviour | |
{ | |
private Action _startFn; | |
private Action _onDestroyFn; | |
private Action _updateFn; | |
public Action UpdateFn | |
{ | |
set { _updateFn = value; } | |
} | |
public Action StartFn | |
{ | |
set { _startFn = value; } | |
} | |
public Action OnDestroyFn | |
{ | |
set { _onDestroyFn = value; } | |
} | |
void Start() | |
{ | |
_startFn(); | |
} | |
void Update() | |
{ | |
_updateFn(); | |
} | |
void OnDestroy() | |
{ | |
_onDestroyFn(); | |
} | |
} |
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
// Example usage: | |
var d = AnonymousMonoBehaviours.Update(() => Debug.Log("I run in the Unity update loop!")); | |
// time passes... | |
d.Dispose(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment