Skip to content

Instantly share code, notes, and snippets.

@eintopf
Created August 11, 2021 16:28
Show Gist options
  • Save eintopf/6512ea0957cf3d9cc9ebb217f5b6d036 to your computer and use it in GitHub Desktop.
Save eintopf/6512ea0957cf3d9cc9ebb217f5b6d036 to your computer and use it in GitHub Desktop.
Allows avoiding repeating HasComponent ? GetComponentData : default pattern. Extension method for Entity Manager in Unity Entities.
using Unity.Entities;
public static class EntityManagerTryExtension
{
public static bool TryGetComponentData<T>(this EntityManager em, in Entity e, out T data) where T : struct, IComponentData
{
if (em.HasComponent<T>(e))
{
data = em.GetComponentData<T>(e);
return true;
}
data = default;
return false;
}
public static T TryGetComponentData<T>(this EntityManager em, in Entity e, T fallback) where T : struct, IComponentData
{
return em.HasComponent<T>(e) ? em.GetComponentData<T>(e) : fallback;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment