Created
August 8, 2018 15:11
-
-
Save jamiebrynes7/f9a4b966e712caa2192964961438474b to your computer and use it in GitHub Desktop.
Strings in an ECS component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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