-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ECSExtensions.cs
84 lines (74 loc) · 2.64 KB
/
ECSExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using Il2CppInterop.Runtime;
using System;
using System.Runtime.InteropServices;
using Unity.Entities;
namespace CrimsonFAQ;
public static class ECSExtensions
{
static EntityManager EntityManager => Core.EntityManager;
public static unsafe void Write<T>(this Entity entity, T componentData) where T : struct
{
// Get the ComponentType for T
var ct = new ComponentType(Il2CppType.Of<T>());
// Marshal the component data to a byte array
byte[] byteArray = StructureToByteArray(componentData);
// Get the size of T
int size = Marshal.SizeOf<T>();
// Create a pointer to the byte array
fixed (byte* p = byteArray)
{
// Set the component data
EntityManager.SetComponentDataRaw(entity, ct.TypeIndex, p, size);
}
}
// Helper function to marshal a struct to a byte array
public static byte[] StructureToByteArray<T>(T structure) where T : struct
{
int size = Marshal.SizeOf(structure);
byte[] byteArray = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(structure, ptr, true);
Marshal.Copy(ptr, byteArray, 0, size);
Marshal.FreeHGlobal(ptr);
return byteArray;
}
public static unsafe T Read<T>(this Entity entity) where T : struct
{
// Get the ComponentType for T
var ct = new ComponentType(Il2CppType.Of<T>());
// Get a pointer to the raw component data
void* rawPointer = EntityManager.GetComponentDataRawRO(entity, ct.TypeIndex);
// Marshal the raw data to a T struct
T componentData = Marshal.PtrToStructure<T>(new IntPtr(rawPointer));
return componentData;
}
public static DynamicBuffer<T> ReadBuffer<T>(this Entity entity) where T : struct
{
return EntityManager.GetBuffer<T>(entity);
}
public static bool TryGetComponent<T>(this Entity entity, out T componentData) where T : struct
{
componentData = default;
if (entity.Has<T>())
{
componentData = entity.Read<T>();
return true;
}
return false;
}
public static bool Has<T>(this Entity entity)
{
var ct = new ComponentType(Il2CppType.Of<T>());
return EntityManager.HasComponent(entity, ct);
}
public static void Add<T>(this Entity entity)
{
var ct = new ComponentType(Il2CppType.Of<T>());
EntityManager.AddComponent(entity, ct);
}
public static void Remove<T>(this Entity entity)
{
var ct = new ComponentType(Il2CppType.Of<T>());
EntityManager.RemoveComponent(entity, ct);
}
}