Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取轨迹渲染器的长度_C#_Unity3d - Fatal编程技术网

C# 获取轨迹渲染器的长度

C# 获取轨迹渲染器的长度,c#,unity3d,C#,Unity3d,如何获得统一绘制的整个轨迹渲染器的长度? 对于线渲染器,我们可以使用线的第一点和第二点来实现这一点,例如: var length = (position2 - position1).magnitude; 但不幸的是,我找不到同样的轨迹渲染器,因为它使用多个点。那么如何实现这一点呢?您可以使用like迭代所有点,例如 public static class TrailRendererExtensions { public static float GetTrailLength(this

如何获得统一绘制的整个轨迹渲染器的长度? 对于线渲染器,我们可以使用线的第一点和第二点来实现这一点,例如:

var length = (position2 - position1).magnitude;

但不幸的是,我找不到同样的轨迹渲染器,因为它使用多个点。那么如何实现这一点呢?

您可以使用like迭代所有点,例如

public static class TrailRendererExtensions
{
    public static float GetTrailLength(this TrailRenderer trailRenderer)
    {
        // You store the count since the created array might be bigger than the actual pointCount

        // Note: apparently the API is wrong?! There it says starting from version 2018.1 the parameter is "out"
        // if you get an error for the "out" anyway or if you use older versions instead use
        //var points = new Vector3[trailRenderer.positionCount]; 
        //var count = trailRenderer.GetPositions(points);
        var count = trailRenderer.GetPositions(out var points);
    
        // If there are not at least 2 points .. well there is nothing to measure
        if(count < 2) return 0f;
    
        var length = 0f;
    
        // Store the first position 
        var start = points[0];

        // Iterate through the rest of positions
        for(var i = 1; i < count; i++)
        {
            // get the current position
            var end = points[i];
            // Add the distance to the last position
            // basically the same as writing
            //length += (end - start).magnitude;
            length += Vector3.Distance(start, end);
            // update the start position for the next iteration
            start = end;
        }
        return length;
    }
}

嗨,谢谢。但是我得到了一个错误,
参数1可能不能与'out'关键字一起传递
您是指
GetPositions
。。那么它在API中是错误的。。这里有
GetPositions(out Vector3[])
Yes表示GetPositions。嗯,奇怪。。以及备选方案:
var points=newvector3[trailRenderer.positionCount];var count=trailRenderer.GetPositions(点数)。。虽然API中有错误,但这很愚蠢。。或者你用的是什么统一版本?可能是后来更改了,我使用的是Unity 2019.4.16f1。我会试试你的替代方案。
var length = yourTrailRenderer.GetTrailLength();