TimedToggle.cs 817 Bytes
Newer Older
1
using UnityEngine;
Markus Schlösser's avatar
Markus Schlösser committed
2
3
using UnityEngine.Events;

4
public class TimedToggle : MonoBehaviour, IResetable {
Markus Schlösser's avatar
Markus Schlösser committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
	[System.Serializable]
	private class BoolEvent : UnityEvent<bool> { }

	[SerializeField] private bool isActive;

	[SerializeField] private float onDuration;
	[SerializeField] private float offDuration;

	[SerializeField] private BoolEvent onStateChange;

	private float time;

	private bool state;

	private void Start() {
20
		ResetToLevelBegin();
Markus Schlösser's avatar
Markus Schlösser committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
	}

	private void Update() {
		if (state && time >= onDuration) {
			time -= onDuration;
			state = false;

			onStateChange.Invoke(false);
		} else if (!state && time >= offDuration) {
			time -= offDuration;
			state = true;

			onStateChange.Invoke(true);
		}

		time += Time.deltaTime;
	}
38
39
40

	public void ResetToLevelBegin() {
		state = isActive;
41
		time = 0;
42
	}
Markus Schlösser's avatar
Markus Schlösser committed
43
}