12
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

SliderとDoTweenでHPバーを作る

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内の画像

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
12
Help us understand the problem. What are the problem?