使用指针操作Jobs示例

用指针传入Jobs操作对于外部类型为传统数据类型的集合来说效率是比较高的,以下是示例代码:

 

using System;
using System.Runtime.InteropServices;
using Unity.Jobs;
using Unity.Burst;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;

public class TestClass : MonoBehaviour
{
    unsafe struct TestJob : IJobParallelFor
    {
        [NativeDisableUnsafePtrRestriction, NoAlias] public Vector3* vecs;

        public void Execute(int i)
        {
            vecs[i] = vecs[i] * 2f;
        }
    }

    private GCHandle mGCHandle;
    private Vector3[] mVectors;


    private void Start()
    {
        mVectors = new Vector3[4];
        Array.Fill(mVectors, Vector3.one);

        mGCHandle = GCHandle.Alloc(mVectors, GCHandleType.Pinned);

        unsafe
        {
            var vectorPtr = (Vector3*)mGCHandle.AddrOfPinnedObject().ToPointer();

            var job = new TestJob()
            {
                vecs = vectorPtr,
            };
            var jobHandle = job.Schedule(4, 2);
            jobHandle.Complete();
        }

        foreach (var item in mVectors)
        {
            Debug.Log(item);
        }//2,2,2...

        mGCHandle.Free();
    }

}

 

posted @ 2025-01-02 22:59  HONT  阅读(47)  评论(0)    收藏  举报