1. RyotaMurohoshi

    Posted

    RyotaMurohoshi
Changes in title
+SliderとDoTweenでHPバーを作る
Changes in tags
Changes in body
Source | HTML | Preview
@@ -0,0 +1,72 @@
+![slider.gif](https://qiita-image-store.s3.amazonaws.com/0/4125/24a27803-2349-424d-6cec-54927cf82df8.gif)
+
+ 上のGIFの画面左上、赤いHPバーのコード例を示します。
+
+```csharp:
+
+using UnityEngine;
+using UnityEngine.UI;
+using DG.Tweening;
+using System.Collections;
+
+namespace Murosta.Utility
+{
+ public class AnimatingRatioIndicator : MonoBehaviour
+ {
+ [SerializeField]
+ Slider frontSlider;
+ [SerializeField]
+ Slider backgroundSlider;
+
+ public void SetRatio(float value)
+ {
+ var clampedValue = Mathf.Clamp01(value);
+
+ frontSlider.value = clampedValue;
+
+ if (backgroundSlider)
+ {
+ backgroundSlider.value = clampedValue;
+ }
+ }
+
+ public Coroutine AnimateRatio(
+ float value,
+ float frontDuration = 0.1F,
+ float backgroundDuration = 0.3F,
+ float backgroundDelay = 0.2F)
+ {
+ return StartCoroutine(AnimateRatioEnumerator(value, frontDuration, backgroundDuration, backgroundDelay));
+ }
+
+ IEnumerator AnimateRatioEnumerator(
+ float value,
+ float frontDuration,
+ float backgroundDuration,
+ float backgroundDelay)
+ {
+ var clampedValue = Mathf.Clamp01(value);
+
+ var frontTweenner = frontSlider.DOValue(clampedValue, frontDuration).SetEase(Ease.InQuad);
+
+ if (backgroundSlider)
+ {
+ yield return backgroundSlider
+ .DOValue(clampedValue, backgroundDuration)
+ .SetDelay(backgroundDelay + frontDuration)
+ .SetEase(Ease.InOutQuad)
+ .WaitForCompletion();
+ }
+ else
+ {
+ yield return frontTweenner.WaitForCompletion();
+ }
+ }
+ }
+}
+```
+
+* 値は、0.0Fから1.0Fの間を指定する([Mathf.InverseLerp](https://docs.unity3d.com/ja/current/ScriptReference/Mathf.InverseLerp.html)が活躍する)
+* `frontSlider`の参照設定は必須
+* `backgroundSlider`の参照設定をすることでGIFのように、時差で減るインジケーターを表現できる
+* アニメーションを行うメソッドは`Coroutine`を返し、`Coroutine in Coroutine`が可能で扱いやすい