Destination array is not long enough to copy all the items in the collection.

230 阅读1分钟

问题背景: 最近实现一个功能辅助类,主要实现的功能是通过 GetCornersNonAlloc 接口获取 到 之间所有的寻路点,并通过得到的这些Corners模拟NavMesh寻路的逻辑。

Unity API: GetCornersNonAlloc

企业微信截图_6579d8c2-2086-464d-b3c4-4399882a692b.png

因为不想在获取Corners时产生GC,所以需要使用NonAlloc的API,并且返回一个Corners的数组; 同理在申请Array数组产生GC,需要预先申请分配好这个数组缓存,也就是在这里产生了问题,具体看代码:

static void InitData()
{
        for (int i = 0; i < 5; ++i)
        {
            Vector3[] corners = new Vector3[30];
            CacheCornersList.Add(corners);
        }
        navCachePath = new NavMeshPath();
}
    
public static void CalculatePath(Vector3 startPos, Vector3 endPos, NavMeshPath navMeshPath, out int cornerCount, out int rIdx)
{
    if (cacheIdx >= CacheCornersList.Count - 1)
    {
        cornerCount = 0;
        rIdx = -1;
        return;
    }
    //先清除缓存的corners数据
    navCachePath?.ClearCorners();
    NavMesh.CalculatePath(startPos, endPos, NavMesh.AllAreas, navCachePath);
    cornerCount = navPath.GetCornersNonAlloc(CacheCornersList[cacheIdx]);
    rIdx = cacheIdx;
    
    cacheIdx++;
}

在实际运行过程中,由于NavMesh比较复杂,计算得到的寻路点比较多,导致了 ”Destination array is not long enough to copy all the items in the collection. “ 的报错,所以,既然要提前申请好数据,尽量将数组的容量扩大一些,避免此类问题出现