Created
March 23, 2025 19:18
-
-
Save rapushka/f3f6801b3b0aa8cd2240a547ccf895b6 to your computer and use it in GitHub Desktop.
EntityParenthoodDebugger Keeps the `Entitas.VisualDebugging.EntityBehaviour`'s hierarchy as it is in your ECS world. if you use some kind of Child-Parent Relationship Components
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
// notes: EntityID is just wrapper around int, and ID is Component with [PrimaryEntityIndex] EntityID | |
// and ChildOf is [EntityIndex] EntityID | |
// this code uses mine Entitas.Generic | |
// if you wanna use this one with usual Entitas - just replace `Entity<GameScope>` with `GameEntity` and stuff | |
public class EntityParenthoodDebugger | |
{ | |
// Key: entity; Value: its parent | |
private readonly Dictionary<EntityID, EntityID> _processedEntities = new(); | |
private ContextObserverBehaviour ContextBehaviour { get; set; } | |
private IEnumerable<EntityBehaviour> EntityBehaviours | |
=> ContextBehaviour.GetComponentsInChildren<EntityBehaviour>(); | |
public void Initialize() | |
{ | |
var contexts = Object.FindObjectsByType<ContextObserverBehaviour>(FindObjectsSortMode.None); | |
foreach (var context in contexts) | |
{ | |
if (context.name.Contains(nameof(GameScope))) | |
ContextBehaviour = context; | |
} | |
} | |
public void OnUpdate() | |
{ | |
if (ContextBehaviour is null) | |
return; | |
foreach (Transform child in ContextBehaviour.transform) | |
{ | |
if (TryGetEntity(child.gameObject, out var entity) && entity.isEnabled) | |
HandleEntity(entity, child); | |
} | |
} | |
private bool TryGetEntity(GameObject gameObject, out Entity<GameScope> entity) | |
{ | |
var isEntityBehaviour = gameObject.TryGetComponent<EntityBehaviour>(out var entityBehaviour); | |
entity = isEntityBehaviour ? (Entity<GameScope>)entityBehaviour.entity : null; | |
return isEntityBehaviour; | |
} | |
private void HandleEntity(Entity<GameScope> entity, Transform childDebugger) | |
{ | |
var entityID = entity.ID(); | |
if (!entity.IsAlive() || !entity.TryGet<ChildOf, EntityID>(out var parentID)) | |
{ | |
if (_processedEntities.ContainsKey(entityID)) | |
{ | |
// but this doesnt work for some reason:( | |
childDebugger.SetParent(ContextBehaviour.transform); | |
_processedEntities.Remove(entityID); | |
} | |
return; | |
} | |
if (_processedEntities.TryGetValue(entityID, out var cashedParentID) | |
&& cashedParentID == parentID) | |
return; | |
foreach (var debugger in EntityBehaviours) | |
{ | |
var parent = (Entity<GameScope>)debugger.entity; | |
if (parent.isEnabled && parentID == parent.ID()) | |
{ | |
childDebugger.SetParent(debugger.transform); | |
_processedEntities[entityID] = parent.ID(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment