Skip to content

Commit 57b2720

Browse files
committed
add monobehaviour extensions
1 parent 923d458 commit 57b2720

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
using UnityEngine;
2+
using Sacristan.Utils.Extensions;
3+
4+
public class MonoBehaviorExtensionsTest : MonoBehaviour
5+
{
6+
private void Start()
7+
{
8+
this.InvokeRepeatingSafe(Tick, 1f, 1f);
9+
this.InvokeSafe(Tock, 2f);
10+
}
11+
12+
private void Tick()
13+
{
14+
Debug.Log("Tick");
15+
}
16+
17+
private void Tock()
18+
{
19+
Debug.Log("Tock");
20+
}
21+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using System;
2+
using System.Collections;
3+
using UnityEngine;
4+
5+
namespace Sacristan.Utils.Extensions
6+
{
7+
public static class MonoBehaviourExtensions
8+
{
9+
public static void InvokeSafe(this MonoBehaviour behavior, System.Action method, float delayInSeconds)
10+
{
11+
behavior.StartCoroutine(InvokeSafeRoutine(method, delayInSeconds));
12+
}
13+
14+
public static void InvokeRepeatingSafe(this MonoBehaviour behavior, System.Action method, float delayInSeconds, float repeatRateInSeconds)
15+
{
16+
behavior.StartCoroutine(InvokeSafeRepeatingRoutine(method, delayInSeconds, repeatRateInSeconds));
17+
}
18+
19+
private static IEnumerator InvokeSafeRepeatingRoutine(System.Action method, float delayInSeconds, float repeatRateInSeconds)
20+
{
21+
yield return new WaitForSeconds(delayInSeconds);
22+
23+
while (true)
24+
{
25+
if (method != null) method.Invoke();
26+
yield return new WaitForSeconds(repeatRateInSeconds);
27+
}
28+
}
29+
30+
private static IEnumerator InvokeSafeRoutine(System.Action method, float delayInSeconds)
31+
{
32+
yield return new WaitForSeconds(delayInSeconds);
33+
if (method != null) method.Invoke();
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)