コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】DOTween で 対象のゲームオブジェクトが破棄されたら Tween も破棄する方法

概要

MissingReferenceException: 
The object of type 'XXXX' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.

DOTween を使っているシーンで他のシーンに遷移する場合は
Tween を破棄しないと上記のようなエラーが発生します

using DG.Tweening;
using UnityEngine;

public class Example : MonoBehaviour
{
    private void Awake()
    {
        transform
            .DOMoveX( 1, 1 )
            .SetLoops( -1 )
            .SetLink( gameObject )
            ;
    }
}

SetLink 関数を使用すると、対象のゲームオブジェクトが破棄されたら
Tween も自動で破棄されるようになります