Unity老师傅填坑记之——System.ArgumentException: Destination array was not long enough

报错信息:

ArgumentException: Destination array was not long enough. Check destIndex and length,
 and the array's lower bounds.

Stack Trace:

System.Array.Copy (System.Array sourceArray, Int32 sourceIndex, System.Array destinationArray, 
Int32 destinationIndex, Int32 length)
System.Collections.Generic.List`1[T].ToArray ()

报错代码:

private List<Vector3> bufVertices = new List<Vector3>();
...
Mesh mesh = new Mesh();
mesh.vertices = bufVertices.ToArray();

分析:
报错信息上写到,“array was not long enough”,但千万别认为是数组长度不够,这里的意思是,申请的数组长度比实际赋值的数组长度小,可能有点歧义,来看调用代码:

mesh.vertices = bufVertices.ToArray();

再看List.ToArray的实现:

[__DynamicallyInvokable]
public T[] ToArray()
{
    T[] array = new T[this._size];
    Array.Copy(this._items, 0, array, 0, this._size);
    return array;
}

可以看到,ToArray的过程中,首先申请了一个新的array,并用当前数组size初始化,然后用Array.Copy进行新的数组赋值。试想一下,如果在新的数组array初始化之后,目标数组长度又发生了变化,会怎样?问题就出在这儿,还原一下问题出现情景:在主线程在进行List.ToArray()操作时,另一个线程正在不亦乐乎的执行bufVertices.Add()操作……看了一下代码,果然用了多线程同时控制bufVertices。

解决:
问题定位到了,那么就很好解决了,只要在bufVertices变动的时候,记得lock。That’s All!

猜你喜欢

转载自blog.csdn.net/u013917120/article/details/79450618