Skip to content

Instantly share code, notes, and snippets.

@dvdfu
Created December 30, 2019 21:09
Show Gist options
  • Save dvdfu/d0d8a518add24564e0da2c13c2e22b6f to your computer and use it in GitHub Desktop.
Save dvdfu/d0d8a518add24564e0da2c13c2e22b6f to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tween {
public delegate void OnUpdate(float progress);
public delegate void OnFinish();
MonoBehaviour mb;
OnFinish onFinish;
IEnumerator coroutine;
public static IEnumerator Start(float duration, OnUpdate onUpdate, bool unscaled = false) {
float t = 0;
while (t < duration) {
onUpdate(t / duration);
t += unscaled ? Time.unscaledDeltaTime : Time.deltaTime;
yield return null;
}
}
public Tween(MonoBehaviour mb) {
this.mb = mb;
onFinish = () => {};
coroutine = null;
}
public void Start(float duration, OnUpdate onUpdate, OnFinish onFinish, bool unscaled = false) {
if (IsAnimating()) {
mb.StopCoroutine(coroutine);
coroutine = null;
}
this.onFinish = onFinish;
coroutine = Animate(duration, onUpdate, onFinish, unscaled);
mb.StartCoroutine(coroutine);
}
public void Stop() {
if (IsAnimating()) {
mb.StopCoroutine(coroutine);
coroutine = null;
onFinish();
}
}
public bool IsAnimating() {
return coroutine != null;
}
IEnumerator Animate(float duration, OnUpdate onUpdate, OnFinish onFinish, bool unscaled) {
yield return Tween.Start(duration, onUpdate, unscaled);
coroutine = null;
onFinish();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment