Skip to content

Instantly share code, notes, and snippets.

@sarkahn
Created February 28, 2020 07:03
Show Gist options
  • Select an option

  • Save sarkahn/271209e13352847a7c8eb2b43f79d91e to your computer and use it in GitHub Desktop.

Select an option

Save sarkahn/271209e13352847a7c8eb2b43f79d91e to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using UnityEngine;
public class FunctionPointerOnComponents : SystemBase
{
[BurstCompile]
public class BurstFuncs
{
[BurstCompile]
public static float Multiply(float a, float b) => a * b;
[BurstCompile]
public static float Add(float a, float b) => a + b;
public delegate float ProcessFloats(float a, float b);
}
public struct FuncComponent : IComponentData
{
public FunctionPointer<BurstFuncs.ProcessFloats> func;
public static implicit operator FunctionPointer<BurstFuncs.ProcessFloats>(FuncComponent c) => c.func;
public static implicit operator FuncComponent(FunctionPointer<BurstFuncs.ProcessFloats> f) => new FuncComponent { func = f };
}
protected override void OnCreate()
{
base.OnCreate();
var addEntity = EntityManager.CreateEntity(typeof(FuncComponent));
var mulEntity = EntityManager.CreateEntity(typeof(FuncComponent));
var add = BurstCompiler.CompileFunctionPointer<BurstFuncs.ProcessFloats>(
BurstFuncs.Add);
var mul = BurstCompiler.CompileFunctionPointer<BurstFuncs.ProcessFloats>(
BurstFuncs.Multiply
);
EntityManager.AddComponentData<FuncComponent>(addEntity, add);
EntityManager.AddComponentData<FuncComponent>(mulEntity, mul);
}
protected override void OnUpdate()
{
NativeArray<float> inFloats = new NativeArray<float>(2, Allocator.TempJob);
inFloats[0] = 5;
inFloats[1] = 10;
NativeArray<float> outFloats = new NativeArray<float>(2, Allocator.TempJob);
// Call FunctionPointers from bursted job
Entities.ForEach((int entityInQueryIndex, FuncComponent f) =>
{
outFloats[entityInQueryIndex] = f.func.Invoke(inFloats[0], inFloats[1]);
}).Schedule();
Job.WithoutBurst().WithCode(() =>
{
// Prints 15, 50
for (int i = 0; i < 2; ++i)
Debug.Log($"Result {i}: {outFloats[i].ToString()}");
}).Schedule();
var deps = Dependency;
inFloats.Dispose(deps);
outFloats.Dispose(deps);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment