Search code examples
c#unity-game-engineintegerinteger-overflow

C# Unity3D Error: List<int>.ToArray() problem


I'm building a complex mesh via C# scripting in Unity3D. Following my generation codes, I pass my triangle data to UnityEngine.Mesh.triangles. My triangle data is stored in a variable typed as List<int>. And the type of UnityEngine.Mesh.triangles is int[]. So I used List<int>.ToArray() method to convert it. But after conversion, some items in the UnityEngine.Mesh.triangles(int[]) are not identical to my triangle data(List<int>). To be more specific, I found that List<int> typed variables could store numbers greater than 65535, but int[] can not do that.

codes:

List<int> ts = new List<int>();
//generation codes
mesh.triangles = ts.ToArray();

And I use this code to test it in Unity:

for (int i = 0; i < mesh.triangles.Length; i++)
            if (mesh.triangles[i] != ts[i]) Debug.Log(mesh.triangles[i].ToString() + " ≠ " + ts[i].ToString()); 

then I get logs such as 0≠65536, indicating that there is a overflow.


Solution

  • but int[] can not do that.

    Of course it can it is an array of int so it supports the entire range of int.

    The issue is most probably not with int[] but probably rather with the Unity mesh API.

    By default a Mesh in Unity can maximum have 65535 vertices. Therefore also the triangles will not store any value above that.

    If you want to have more vertices than that you need to change the Mesh.indexFormat to IndexFormat.UInt32