Skip to content

Instantly share code, notes, and snippets.

@jamiebrynes7
Created August 8, 2018 15:11
Show Gist options
  • Save jamiebrynes7/f9a4b966e712caa2192964961438474b to your computer and use it in GitHub Desktop.
Save jamiebrynes7/f9a4b966e712caa2192964961438474b to your computer and use it in GitHub Desktop.
Strings in an ECS component
// Allocation singleton class
public static class StringProvider
{
private static readonly Dictionary<uint, string> Storage = new Dictionary<uint, string>();
private static uint nextHandle = 0;
public static uint Allocate(string value = default(string))
{
var handle = GetNextHandle()
Storage.Add(handle, value);
return handle;
}
public static string Get(uint handle)
{
if (!Storage.TryGetValue(handle, out var value))
{
throw new ArgumentException($"StringProvider does not contain handle {handle}");
}
return value;
}
public static void Set(uint handle, string value)
{
if (!Storage.ContainsKey(handle))
{
throw new ArgumentException($"StringProvider does not contain handle {handle}");
}
Storage[handle] = value;
}
public static void Free(uint handle)
{
Storage.Remove(handle);
}
private static uint GetNextHandle()
{
while (Storage.ContainsKey(++nextHandle))
{
}
return nextHandle;
}
}
// You can then write a component like the following:
public struct MyComponent : IComponentData
{
public uint Handle;
}
// You can then write a component like the following:
public struct MyComponent : IComponentData
{
public uint Handle;
}
// And then create it like the following:
var component = new MyComponent();
component.handle = StringProvider.Allocate("my-string");
entityManager.AddComponentData(entity, component)
// And use it:
var component = entityManager.GetComponentData<MyComponent>(entity);
var s = StringProvider.Get(component.Handle);
s = "new-string";
StringProvider.Set(component.Handle, s);
// Just make sure to free it!
var component = entityManager.GetComponentData<MyComponent>(entity);
StringProvider.Free(component.Handle);
entityManager.RemoveComponent<MyComponent>(entity);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment