LoginSignup
11
12

More than 5 years have passed since last update.

SliderとDoTweenでHPバーを作る

Last updated at Posted at 2017-02-27

slider.gif

 Unityにおいて、上記GIFの赤いHPバーを実現するためのコード例を示します。


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();
            }
        }
    }
}
  • アニメーションはDoTweenを利用
  • 値は、0.0Fから1.0Fの間を指定する(Mathf.InverseLerpが活躍すると、0.0Fから1.0Fの値に簡単に変換可能)
  • frontSliderの参照設定は必須
  • backgroundSliderの参照設定をすることでGIFのように、時差で減るインジケーターを表現できる
  • アニメーションを行うメソッドはCoroutineを返し、Coroutine in Coroutineが可能で扱いやすい

GIF内の画像

11
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12