Description
I already have the solution. Just open an issue to let other users know.
Error log
ArgumentException: Object contains non-primitive or non-blittable data.
at Stella3D.SharedArray`2[T,TNative].Initialize () [0x00000] in <00000000000000000000000000000000>:0
at NewBehaviourScript.CreateSharedArray[T] () [0x00000] in <00000000000000000000000000000000>:0
at NewBehaviourScript.OnGUI () [0x00000] in <00000000000000000000000000000000>:0
How to reproduce
I made a simple script to reproduce.
void OnGUI()
{
if (GUI.Button(new Rect(10, 10, 300, 30), "Create NativeArray A"))
{
CreateNativeArray<CustomStructA>();
}
if (GUI.Button(new Rect(10, 50, 300, 30), "Create SharedArray A"))
{
CreateSharedArray<CustomStructA>();
}
}
private void CreateNativeArray<T>() where T : unmanaged
{
Debug.Log("CreateNativeArray " + typeof(T));
// Create a native array.
NativeArray<T> nativeArray = new NativeArray<T>(10, Allocator.Persistent);
nativeArray.Dispose();
}
private void CreateSharedArray<T>() where T : unmanaged
{
Debug.Log("CreateSharedArray " + typeof(T));
// Create a shared array.
Stella3D.SharedArray<T> sharedArray = new Stella3D.SharedArray<T>(10);
sharedArray.Dispose();
}
public struct CustomStructA {
public bool booleanVar;
}
- Attach the script on a gameobject and build a development build in IL2CPP Windows.
- Press the button Create SharedArray A and you will see that creating
NativeArray<CustomStructA>
worked, butSharedArray<CustomStructA>
throwed the exception.
Environment:
- Unity 2021 LTS and above.
- Windows IL2CPP (It worked properly with Mono)
How does it happen
There is an Unity issue about the same error but occurs calling NativeArray.Copy
.
https://issuetracker.unity3d.com/issues/argumentexception-error-occurs-in-copy-method-of-nativearray-class-when-building-with-windows-il2cpp
I think it is the same internal issue but occured in different functions. Since it fixed in 2022.2.19f1, this issue goes away from Unity 2022 as well.
And there is a dicussion about this issue in 2020
https://forum.unity.com/threads/argument-exception-on-windows-il2cpp-build-with-burst-jobs.836059/
As tertle said, IL2CPP and Burst together may have issues with bools. This is how I found out where the issue was coming from.
Struct with bool
fields causes this issue.
Solution / Workaround
Add this attribute [MarshalAs(UnmanagedType.U1)]
to your boolean fields.
public struct CustomStructA {
[MarshalAs(UnmanagedType.U1)]
public bool booleanVar;
}
I found there is bool2
in Unity.Mathematics
package and it worked well.
That is the attribute they used for bool struct series.
https://github.com/Unity-Technologies/Unity.Mathematics/blob/master/src/Unity.Mathematics/bool2.gen.cs