Search Unity

Is it possible to skip safety checks for specific lines of code?

Discussion in 'Entity Component System' started by daschatten, Jan 10, 2020.

  1. daschatten

    daschatten

    Joined:
    Jul 16, 2015
    Posts:
    208
    In my custom render system (replacement for RenderMeshSystemV2) i use

    Code (CSharp):
    1. values.AsArray().Reinterpret<Matrix4x4>().CopyTo(_matrices);
    The _matrices is a Matrix4x4[] of length 1023. The values array contains a variable number of items. In editor i get this exception:

    Code (CSharp):
    1. source and destination length must be the same
    In build it works fine. I assume the safety checks are preventing this code from runnning in editor.

    Is there a way to skip the safety checks for specific lines of code?
     
  2. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    4,264
    Grab a NativeSlice of _matrices with a length of values and use CopyTo on the slice.
     
  3. daschatten

    daschatten

    Joined:
    Jul 16, 2015
    Posts:
    208
    _matrices is a managed array (Matrix4x4[]), therefore this doesn't work without conversion and gc alloc.
     
  4. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,759
    You don't have allocate anything. You can simply make your native container point to the same memory location of your _matrices array.

    Something like this should work off top of my head. there is probably an even cleaner way of doing it.

    Code (CSharp):
    1.  
    2. var values = new NativeList<Matrix4x4>(10, Allocator.Temp);
    3. var _matrices = new Matrix4x4[1024];
    4. fixed (Matrix4x4* address = _matrices)
    5. {
    6.     var n = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<Matrix4x4>(
    7.         address,
    8.         values.Length, // note uses values.length
    9.         Allocator.Invalid);
    10. #if ENABLE_UNITY_COLLECTIONS_CHECKS
    11.       NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref n, AtomicSafetyHandle.Create()); // wrap this in safety attribute which
    12. #endif
    13.  
    14.     values.AsArray().Reinterpret<Matrix4x4>().CopyTo(n);
    15. }
    16.