コガネブログ

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

【Unity】LineRenderer の positionCount を Tween させる拡張メソッド

ソースコード

using System.Collections.Generic;
using DG.Tweening;
using Unity.Collections;
using UnityEngine;

namespace Kogane
{
    /// <summary>
    /// LineRenderer 型の DOTween 関連の拡張メソッド
    /// </summary>
    public static class DOTweenLineRendererExtensionMethods
    {
        //================================================================================
        // 関数(static)
        //================================================================================
        /// <summary>
        /// positionCount の Tween を再生します
        /// </summary>
        public static Tweener DOPositionCount
        (
            this LineRenderer    self,
            NativeArray<Vector3> positions,
            float                duration
        )
        {
            void Getter( float x )
            {
                var newPositionCount = Mathf.Clamp( ( int )x, 0, positions.Length );
                var oldPositionCount = self.positionCount;

                if ( newPositionCount == oldPositionCount ) return;

                self.positionCount = newPositionCount;

                for ( var i = oldPositionCount; i < newPositionCount; i++ )
                {
                    self.SetPosition( i, positions[ i ] );
                }
            }

            self.positionCount = 0;

            return DOTween.To
            (
                setter: Getter,
                startValue: 0,
                endValue: positions.Length,
                duration: duration
            );
        }

        /// <summary>
        /// positionCount の Tween を再生します
        /// </summary>
        public static Tweener DOPositionCount
        (
            this LineRenderer      self,
            IReadOnlyList<Vector3> positions,
            float                  duration
        )
        {
            void Getter( float x )
            {
                var newPositionCount = Mathf.Clamp( ( int )x, 0, positions.Count );
                var oldPositionCount = self.positionCount;

                if ( newPositionCount == oldPositionCount ) return;

                self.positionCount = newPositionCount;

                for ( var i = oldPositionCount; i < newPositionCount; i++ )
                {
                    self.SetPosition( i, positions[ i ] );
                }
            }

            self.positionCount = 0;

            return DOTween.To
            (
                setter: Getter,
                startValue: 0,
                endValue: positions.Count,
                duration: duration
            );
        }
    }
}

使用例

m_positions = new NativeArray<Vector3>( m_lineRenderer.positionCount, Allocator.Persistent );
m_lineRenderer.GetPositions( m_positions );

m_lineRenderer
    .DOPositionCount( m_positions, m_duration )
    .SetEase( m_ease )
    .SetLink( gameObject )
;