unity build_error ai_generated true

IL2CPP错误:System.InvalidCastException:指定的强制转换无效。数组类型'System.Int32[]'无法分配给类型'System.Single[]'的数组

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

其他格式: JSON · Markdown 中文 · English
80%修复率
82%置信度
1证据数
2024-01-20首次发现

版本兼容性

版本状态引入弃用备注
Unity 2022.3 active
Unity 2023.2 active
IL2CPP 1.0 active

根因分析

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

English

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

官方文档

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 50% 失败

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

  2. 75% 失败

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