Use GetMut in Entity.Set to avoid unnecessary copy

copygirl 1 year ago
parent 46e171940e
commit 13f1d5b23a
  1. 19
      src/gaemstone.ECS/EntityRef.cs

@ -116,8 +116,8 @@ public unsafe class EntityRef
public override ref T GetMut<T>(Id id)
{
// Value is added if it doesn't exist on the entity.
var ptr = ecs_get_mut_id(World, this, id);
// NOTE: Value is added if it doesn't exist on the entity.
return ref Unsafe.AsRef<T>(ptr);
}
@ -125,22 +125,13 @@ public unsafe class EntityRef
=> ecs_modified_id(World, this, id);
public override EntityRef Set<T>(Id id, in T value)
{
var size = (ulong)Unsafe.SizeOf<T>();
fixed (T* ptr = &value)
if (ecs_set_id(World, this, id, size, ptr).Data == 0)
throw new InvalidOperationException();
return this;
}
{ GetMut<T>(id) = value; return this; }
public override EntityRef Set<T>(Id id, T obj) where T : class
{
if (obj == null) throw new ArgumentNullException(nameof(obj));
var size = (ulong)sizeof(ReferenceHandle);
// Dispose this handle afterwards, since Flecs clones it.
using var handle = ReferenceHandle.Alloc(obj);
if (ecs_set_id(World, this, id, size, &handle).Data == 0)
throw new InvalidOperationException();
ref var handle = ref GetMut<ReferenceHandle>(id);
handle.Dispose(); // Free previously handle, if any.
handle = ReferenceHandle.Alloc(obj);
return this;
}

Loading…
Cancel
Save