unity build_error ai_generated true

IL2CPP error: System.InvalidCastException: Specified cast is not valid. Array type 'System.Int32[]' cannot be assigned to array of type 'System.Single[]'

ID: unity/il2cpp-array-type-mismatch

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
1Evidence
2024-01-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Unity 2022.3 active
Unity 2023.2 active
IL2CPP 1.0 active

Root Cause

IL2CPP code stripping or type conversion issue where an int array is incorrectly cast to a float array, often due to unsafe code or marshaling.

generic

中文

IL2CPP代码剥离或类型转换问题,其中整数数组被错误地转换为浮点数组,通常是由于不安全的代码或封送处理。

Official Documentation

https://docs.unity3d.com/Manual/IL2CPP-ErrorCodes.html

Workarounds

  1. 85% success Avoid direct array type conversion; use Array.ConvertAll() or LINQ Select() to create a new array: float[] floatArray = intArray.Select(i => (float)i).ToArray();
    Avoid direct array type conversion; use Array.ConvertAll() or LINQ Select() to create a new array: float[] floatArray = intArray.Select(i => (float)i).ToArray();
  2. 70% success Mark the method with [Il2CppSetOption(Option.NullChecks, false)] to suppress the IL2CPP check, but only if the cast is safe (not recommended for production).
    Mark the method with [Il2CppSetOption(Option.NullChecks, false)] to suppress the IL2CPP check, but only if the cast is safe (not recommended for production).

中文步骤

  1. 避免直接数组类型转换;使用Array.ConvertAll()或LINQ Select()创建新数组:float[] floatArray = intArray.Select(i => (float)i).ToArray();
  2. 使用[Il2CppSetOption(Option.NullChecks, false)]标记方法以抑制IL2CPP检查,但仅在转换安全时使用(不推荐用于生产)。

Dead Ends

Common approaches that don't work:

  1. 50% fail

    Disabling code stripping entirely may fix the cast but increases build size and hides the real issue; the cast is still incorrect.

  2. 75% fail

    Adding explicit casts in C# code does not help because the error occurs during IL2CPP conversion of array types, not at runtime.