LoginSignup
35
21

More than 5 years have passed since last update.

[Unity] DOTweenでの各ループ終了時にCallback処理を挟みたい

Last updated at Posted at 2017-07-10

環境

  • Unity5.5.2f
  • DOTween v1.1.600

結論

Tween.OnStepComplete を使おう

背景

  • 例えば、以下のようなゲージ増加のTweenを用意する
  • OnComplete を使用することで終了時に Debug.Log が実行される
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Image))]
public class DOTweenTest : MonoBehaviour
{
    private void OnEnable()
    {
        this.GetComponent<Image>()
            .DOFillAmount(1.0f, 1.0f)
            .OnComplete(() => Debug.Log("completed"))
            .Play();
    }
}

tween1.gif

  • これにループ処理を挟み、ゲージが貯まる度に挙動を挟みたい
  • まずは以下のコードを実行してみる
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Image))]
public class DOTweenTest : MonoBehaviour
{
    private void OnEnable()
    {
        this.GetComponent<Image>()
            .DOFillAmount(1.0f, 1.0f)
            .OnComplete(() => Debug.Log("completed"))
            .SetLoops(-1, LoopType.Restart)
            .Play();
    }
}

tween2.gif

Sequence.AppendCallback

using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Image))]
public class DOTweenTest : MonoBehaviour
{
    private void OnEnable()
    {
        Sequence sequence = DOTween.Sequence()
            .Append(this.GetComponent<Image>().DOFillAmount(1.0f, 1.0f))
            .AppendCallback(() => Debug.Log("completed"))
            .SetLoops(-1, LoopType.Restart)
            .Play();
    }
}

tween4.gif

  • 挙動的には問題なさそうである
  • 但しこれもやはり問題があり SetLoops(-1, LoopType.Yoyo) に対応できていないということだ
    • LoopType.Yoyo は処理を折り返し実行する関数 (ヨーヨーみたいに)
  • 手元で実行すると往路での Debug.Log は呼ばれるが、復路では呼ばれないことが確認出来た
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Image))]
public class DOTweenTest : MonoBehaviour
{
    private void OnEnable()
    {
        Sequence sequence = DOTween.Sequence()
            .Append(this.GetComponent<Image>().DOFillAmount(1.0f, 1.0f))
            .AppendCallback(() => Debug.Log("completed"))
            .SetLoops(-1, LoopType.Yoyo)
            .Play();
    }
}

tween5.gif

Tween.OnStepComplete

  • http://dotween.demigiant.com/documentation.php
  • DOTween側で何かしら関数用意してそうだなぁと思ってドキュメント読んでいたら OnStepComplete を発見した
  • a single loop cycle が完了したときに発火してくれるコールバック
  • まさにこれだ!ということで試してみる
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Image))]
public class DOTweenTest : MonoBehaviour
{
    private void OnEnable()
    {
        this.GetComponent<Image>()
            .DOFillAmount(1.0f, 1.0f)
            .OnStepComplete(() => Debug.Log("completed!"))
            .SetLoops(-1, LoopType.Yoyo)
            .Play();
    }
}

tween3.gif

  • 意図通りの挙動になった!
35
21
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
35
21