コガネブログ

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

【Unity】SplineContainer を LineRenderer に反映する拡張メソッド

ソースコード

using Unity.Collections;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.Splines;

namespace Kogane
{
    public static class LineRendererExtensionMethods
    {
        public static void UpdateFromSplineContainer
        (
            this LineRenderer self,
            SplineContainer   splineContainer,
            int               segments
        )
        {
            var points = new NativeArray<Vector3>( segments, Allocator.Temp );

            try
            {
                using var spline = new NativeSpline
                (
                    splineContainer.Spline,
                    self.useWorldSpace
                        ? splineContainer.transform.localToWorldMatrix
                        : float4x4.identity
                );

                var total = segments - 1f;

                for ( var i = 0; i < segments; ++i )
                {
                    var point = spline.EvaluatePosition( i / total );
                    point.z     = 0;
                    points[ i ] = point;
                }

                self.positionCount = segments;
                self.SetPositions( points );
            }
            finally
            {
                points.Dispose();
            }
        }
    }
}

参考サイト様