-
Notifications
You must be signed in to change notification settings - Fork 1
LDtk EntityRef
In LDtk, entities often need to reference other entities. A pressure plate needs to know which door to open. A quest giver needs to know which NPC to point to. A trap needs to know which lever controls it.
LDtk stores these references as entity reference fields. The problem is that most integrations give you raw JSON data and force you to manually parse these references.
Void provides a fully typed LDtkEntityRef struct that contains all the reference data. You get the entity ID and the IDs of the layer, level, and world that contain it. You can then look up the referenced entity from the map.
The LDtkEntityRef struct represents a reference to an entity instance.
public readonly struct LDtkEntityRef
{
public string EntityId { get; }
public string LayerId { get; }
public string LevelId { get; }
public string WorldId { get; }
}| Property | Description |
|---|---|
EntityId |
The ID of the referenced entity instance |
LayerId |
The ID of the layer containing the entity |
LevelId |
The ID of the level containing the entity |
WorldId |
The ID of the world containing the entity |
Entity references are used in LDtk settings that point to other entities.
var settings = entity.Settings;
// Get an entity reference setting
if (LDtkSetting.TryGetEntityRefSetting(settings, "TargetEntity", out var entityRef))
{
// Use the entity reference
}// Get an entity reference
if (LDtkSetting.TryGetEntityRefSetting(settings, "TargetEntity", out var entityRef))
{
// Get the referenced entity from the map
if (map.TryGetEntityById(entityRef.EntityId, out var targetEntity))
{
// Use the target entity
Console.WriteLine($"Referenced entity: {targetEntity.Name}");
}
}You can check if an entity reference is valid.
if (LDtkSetting.TryGetEntityRefSetting(settings, "TargetEntity", out var entityRef))
{
// Check if the entity reference has a valid ID
if (!string.IsNullOrEmpty(entityRef.EntityId))
{
// The reference is valid
var targetEntity = map.GetEntityById(entityRef.EntityId);
}
}// Load the map
var map = AssetManager.Instance.Load<LDtkMap>("levels/world.ldtk");
// Get a level
var level = map.GetLevelByName("Level_01");
// Find an entity with a target reference
foreach (var layer in level.Layers)
{
if (layer.Type == LDtkLayerType.Entities)
{
var entities = layer.InstanceAs<LDtkEntityInstance>();
foreach (var entity in entities)
{
if (LDtkSetting.TryGetEntityRefSetting(entity.Settings, "Target", out var targetRef))
{
if (!string.IsNullOrEmpty(targetRef.EntityId))
{
var target = map.GetEntityById(targetRef.EntityId);
Console.WriteLine($"Entity: {entity.Name} targets: {target.Name}");
}
}
}
}
}Home · Getting Started · Rendering · Custom Renderers · GitHub · Report an Issue
Built with VOID Engine · MIT License