Creating a Mini Metro clone using Unity’s Entity Component System (ECS) with DOTS (Data-Oriented Technology Stack) and the Burst compiler is an excellent way to leverage performance benefits, especially for handling numerous entities efficiently. This guide will walk you through creating the simplest functionality: placing stations and connecting lines between them with both mouse and touch input support. We'll use Unity’s 2D environment.
Table of Contents
- Prerequisites
- Project Setup
- Defining Components
- Creating Prefabs and Entity Archetypes
- Implementing Systems
- Rendering Entities
- Handling Both Mouse and Touch Input
- Complete Code Listing
- Final Notes
Prerequisites
- Unity Hub: Version 2020.1 or newer is recommended for better DOTS support.
- Unity Editor: Installed via Unity Hub.
- Basic Knowledge: Familiarity with Unity’s interface, C#, and basic ECS concepts.
Project Setup
-
Create a New Project:
- Open Unity Hub.
- Click on New.
- Select the 2D template.
- Name your project, e.g.,
MiniMetroClone.
- Click Create.
-
Install Required Packages:
Unity’s ECS and related packages are essential for this project.
- Entities: Core ECS framework.
- Hybrid Renderer: For rendering ECS entities with GameObjects.
- Unity Physics: If needed for interactions (optional in this context).
Steps to Install:
- Open Window > Package Manager.
- Select Packages: Unity Registry from the dropdown.
- Search for and install the following packages:
- Entities
- Hybrid Renderer 2D
- Mathematics (usually a dependency)
- Ensure all packages are compatible with your Unity version.
-
Enable DOTS Support:
- Go to Edit > Project Settings > Player.
- Under Other Settings, ensure that Scripting Backend is set to IL2CPP or Mono based on your preference.
- No additional steps are typically needed for DOTS as of recent Unity versions.
Defining Components
Components are data containers in ECS. We’ll define components for Stations, Lines, and User Interaction States.
- StationComponent: Represents a station in the game.
using Unity.Entities;
using Unity.Mathematics;
public struct StationComponent : IComponentData
{
public float2 Position;
public Entity ConnectedLine;
}
- LineComponent: Represents a line connecting stations.
using Unity.Entities;
using Unity.Mathematics;
public struct LineComponent : IComponentData
{
public Entity[] ConnectedStations;
}
- DraggingComponent: Represents the current dragging state.
using Unity.Entities;
public struct DraggingComponent : IComponentData
{
public Entity FromStation;
}
- Render Components: For rendering, we’ll use Unity’s Hybrid Renderer components, so additional data structures aren’t necessary.
Creating Prefabs and Entity Archetypes
To efficiently create entities, we’ll define prefabs for stations and lines.
-
Station Prefab:
-
Line Prefab:
Note: Unity doesn’t provide a default 2D Line Renderer in older versions, so you might need to create a custom line renderer or use the SpriteShape package for lines. For simplicity, we'll assume a compatible Line Renderer is available.
Implementing Systems
We will create three main systems:
- InputSystem: Handles user input (mouse and touch).
- StationPlacementSystem: Manages placement of stations.
- LineConnectionSystem: Handles connecting lines between stations.
1. Input System
This system captures user input and updates the ECS state accordingly.
using Unity.Entities;
using Unity.Collections;
using UnityEngine;
using Unity.Mathematics;
using Unity.Transforms;
public class InputSystem : SystemBase
{
protected override void OnUpdate()
{
var inputDeps = Dependency;
// Capture mouse position
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
// Check for touch input
#if UNITY_ANDROID || UNITY_IOS
bool isTouching = Input.touchCount > 0;
if (isTouching)
{
Touch touch = Input.GetTouch(0);
mousePos = Camera.main.ScreenToWorldPoint(touch.position);
}
#endif
// Start dragging
if (Input.GetMouseButtonDown(0))
{
Entities.WithAll<StationComponent>().ForEach((Entity entity, ref StationComponent station, in Translation translation) =>
{
float distance = math.distance(station.Position, mousePos);
if (distance < 0.5f) // Assuming station radius is 0.5
{
// Initiate dragging
var dragging = new DraggingComponent { FromStation = entity };
EntityManager.AddComponentData(this.Entity, dragging);
}
}).WithoutBurst().Run();
}
// Update dragging
if (Input.GetMouseButton(0))
{
Entities.WithAll<DraggingComponent>().ForEach((ref DynamicBuffer<LinePositionBuffer> lineBuffer) =>
{
// Update temporary line positions
}).WithoutBurst().Run();
}
// End dragging
if (Input.GetMouseButtonUp(0))
{
Entities.WithAll<DraggingComponent>().ForEach((Entity draggingEntity, ref DraggingComponent dragging) =>
{
// Check if released over a station
Entities.WithAll<StationComponent>().ForEach((Entity targetEntity, ref StationComponent targetStation) =>
{
float distance = math.distance(targetStation.Position, mousePos);
if (distance < 0.5f && targetEntity != dragging.FromStation)
{
// Create or update line entity connecting dragging.FromStation and targetEntity
// Implementation in LineConnectionSystem
}
}).Run();
// Remove dragging component
EntityManager.RemoveComponent<DraggingComponent>(draggingEntity);
}).WithoutBurst().Run();
}
}
}
Note: The above code is a simplified version to illustrate the concept. We will refine it in complete code section.
2. Station Placement System
This system allows users to place stations by clicking on empty space.
using Unity.Entities;
using Unity.Transforms;
using Unity.Mathematics;
using UnityEngine;
public class StationPlacementSystem : SystemBase
{
private Entity stationPrefab;
private BeginInitializationEntityCommandBufferSystem ecbSystem;
protected override void OnCreate()
{
base.OnCreate();
// Assume StationPrefab is assigned via a public field or other means
stationPrefab = EntityManager.CreateEntity(); // Replace with proper prefab assignment
ecbSystem = World.GetOrCreateSystem<BeginInitializationEntityCommandBufferSystem>();
}
protected override void OnUpdate()
{
var ecb = ecbSystem.CreateCommandBuffer().AsParallelWriter();
// Handle input for placing new stations
if (Input.GetMouseButtonDown(1)) // Right-click to place station
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Entity newStation = ecb.Instantiate(0, stationPrefab);
ecb.SetComponent(0, newStation, new Translation { Value = new float3(mousePos.x, mousePos.y, 0) });
ecb.SetComponent(0, newStation, new StationComponent { Position = mousePos, ConnectedLine = Entity.Null });
}
// Similarly handle touch input for mobile
#if UNITY_ANDROID || UNITY_IOS
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
Vector2 touchPos = Camera.main.ScreenToWorldPoint(touch.position);
Entity newStation = ecb.Instantiate(0, stationPrefab);
ecb.SetComponent(0, newStation, new Translation { Value = new float3(touchPos.x, touchPos.y, 0) });
ecb.SetComponent(0, newStation, new StationComponent { Position = touchPos, ConnectedLine = Entity.Null });
}
}
#endif
ecbSystem.AddJobHandleForProducer(Dependency);
}
}
Note: We'll integrate station placement within the InputSystem for coherence in the final code.
3. Line Connection System
This system manages the creation and updating of lines connecting stations.
using Unity.Entities;
using Unity.Transforms;
using Unity.Mathematics;
using UnityEngine;
public class LineConnectionSystem : SystemBase
{
private Entity linePrefab;
private BeginInitializationEntityCommandBufferSystem ecbSystem;
protected override void OnCreate()
{
base.OnCreate();
// Assume LinePrefab is assigned via a public field or other means
linePrefab = EntityManager.CreateEntity(); // Replace with proper prefab assignment
ecbSystem = World.GetOrCreateSystem<BeginInitializationEntityCommandBufferSystem>();
}
protected override void OnUpdate()
{
// Check for dragging completion to create lines
// Implementation based on DraggingComponent
}
}
Note: This is a placeholder. We'll implement line creation in the final code.
Rendering Entities
Using Unity’s Hybrid Renderer (specifically for 2D), entities will be automatically rendered based on their components (e.g., Translation for position and SpriteRenderer or LineRenderer for visuals).
-
Station Rendering:
The StationPrefab with a SpriteRenderer will handle visual representation. Ensure that each station entity has the necessary render components via the prefab.
-
Line Rendering:
For lines, if using a LineRenderer, ensure that the line entities have positions updated based on connected stations.
Handling Both Mouse and Touch Input
To support both PC (mouse) and mobile (touch), abstract the input handling to consider both input types.
-
Unified Input Handling:
Create a utility to fetch the primary input position, whether from mouse or touch.
-
Event Handling:
Ensure events like Click, Drag Start, Drag Update, and Drag End are appropriately processed.
Complete Code Listing
Below is a comprehensive implementation incorporating the above aspects. This example uses Unity’s ECS with the Hybrid Renderer for 2D and supports both mouse and touch inputs.
- Components
// StationComponent.cs
using Unity.Entities;
using Unity.Mathematics;
[GenerateAuthoringComponent]
public struct StationComponent : IComponentData
{
public float2 Position;
// For simplicity, we'll store connected lines as DynamicBuffer-like data if needed
}
// LineComponent.cs
using Unity.Entities;
using Unity.Mathematics;
[GenerateAuthoringComponent]
public struct LineComponent : IComponentData
{
public Entity StartStation;
public Entity EndStation;
}
// DraggingComponent.cs
using Unity.Entities;
[GenerateAuthoringComponent]
public struct DraggingComponent : IComponentData
{
public Entity FromStation;
}
- Authoring Scripts
Ensure prefabs are assigned correctly in the editor.
// StationAuthoring.cs
using UnityEngine;
using Unity.Entities;
public class StationAuthoring : MonoBehaviour, IConvertGameObjectToEntity
{
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
var translation = gameObject.GetComponent<Transform>().position;
dstManager.AddComponentData(entity, new StationComponent
{
Position = new float2(translation.x, translation.y)
});
}
}
// LineAuthoring.cs
using UnityEngine;
using Unity.Entities;
public class LineAuthoring : MonoBehaviour, IConvertGameObjectToEntity
{
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
// Initial empty, connections are managed via the system
dstManager.AddComponentData(entity, new LineComponent
{
StartStation = Entity.Null,
EndStation = Entity.Null
});
}
}
- Systems
InputSystem.cs
using Unity.Entities;
using Unity.Collections;
using Unity.Mathematics;
using UnityEngine;
using Unity.Transforms;
using UnityEngine.InputSystem;
public partial class InputSystem : SystemBase
{
private BeginInitializationEntityCommandBufferSystem ecbSystem;
private Entity stationPrefab;
private Entity linePrefab;
protected override void OnCreate()
{
base.OnCreate();
ecbSystem = World.GetOrCreateSystem<BeginInitializationEntityCommandBufferSystem>();
// Assuming prefabs are assigned via subscenes or other mechanisms
}
protected override void OnUpdate()
{
var ecb = ecbSystem.CreateCommandBuffer().AsParallelWriter();
// Assuming prefabs are retrieved once
if (stationPrefab == Entity.Null || linePrefab == Entity.Null)
{
Entities.WithAll<StationComponent>().WithoutBurst().ForEach((Entity entity, ref StationComponent station) =>
{
stationPrefab = entity;
}).Run();
Entities.WithAll<LineComponent>().WithoutBurst().ForEach((Entity entity, ref LineComponent line) =>
{
linePrefab = entity;
}).Run();
}
// Handle Dragging
if (Input.GetMouseButtonDown(0))
{
Vector2 pointerPos = GetPointerPosition();
Entities.WithAll<StationComponent>().ForEach((Entity entity, in StationComponent station) =>
{
float distance = math.distance(station.Position, pointerPos);
if (distance <= 0.5f) // Adjust based on station size
{
// Start dragging
ecb.AddComponent(0, entity, new DraggingComponent { FromStation = entity });
}
}).Run();
}
if (Input.GetMouseButtonUp(0))
{
Vector2 pointerPos = GetPointerPosition();
Entities.WithAll<DraggingComponent>().ForEach((Entity draggingEntity, in DraggingComponent dragging) =>
{
// Find if pointer is over another station
Entities.WithAll<StationComponent>().ForEach((Entity targetEntity, in StationComponent target) =>
{
float distance = math.distance(target.Position, pointerPos);
if (distance <= 0.5f && targetEntity != dragging.FromStation)
{
// Create a new line connecting FromStation and target
Entity newLine = ecb.Instantiate(0, linePrefab);
ecb.SetComponent(0, newLine, new LineComponent
{
StartStation = dragging.FromStation,
EndStation = targetEntity
});
// Optionally, update stations to reference the new line
// Skipped for simplicity
}
}).Run();
// Remove DraggingComponent
ecb.RemoveComponent<DraggingComponent>(0, draggingEntity);
}).Run();
}
// Optionally, handle dragging visuals here
// Handle Station Placement
if (Input.GetMouseButtonDown(1)) // Right-click to place station
{
Vector2 pointerPos = GetPointerPosition();
Entity newStation = ecb.Instantiate(0, stationPrefab);
ecb.SetComponent(0, newStation, new Translation { Value = new float3(pointerPos, 0) });
ecb.SetComponent(0, newStation, new StationComponent { Position = pointerPos });
}
#if UNITY_ANDROID || UNITY_IOS
// Handle touch input
foreach (var touch in UnityEngine.Input.touches)
{
Vector2 touchPos = Camera.main.ScreenToWorldPoint(touch.position);
switch (touch.phase)
{
case TouchPhase.Began:
Entities.WithAll<StationComponent>().ForEach((Entity entity, ref StationComponent station) =>
{
float distance = math.distance(station.Position, touchPos);
if (distance <= 0.5f)
{
// Start dragging
ecb.AddComponent<DraggingComponent>(0, entity, new DraggingComponent { FromStation = entity });
}
}).Run();
break;
case TouchPhase.Ended:
Entities.WithAll<DraggingComponent>().ForEach((Entity draggingEntity, ref DraggingComponent dragging) =>
{
// Find if touch released over another station
Entities.WithAll<StationComponent>().ForEach((Entity targetEntity, ref StationComponent target) =>
{
float distance = math.distance(target.Position, touchPos);
if (distance <= 0.5f && targetEntity != dragging.FromStation)
{
// Create a new line connecting FromStation and target
Entity newLine = ecb.Instantiate(0, linePrefab);
ecb.SetComponent(0, newLine, new LineComponent
{
StartStation = dragging.FromStation,
EndStation = targetEntity
});
// Optionally, update stations to reference the new line
// Skipped for simplicity
}
}).Run();
// Remove DraggingComponent
ecb.RemoveComponent<DraggingComponent>(0, draggingEntity);
}).Run();
break;
}
}
#endif
ecbSystem.AddJobHandleForProducer(Dependency);
}
private Vector2 GetPointerPosition()
{
#if UNITY_ANDROID || UNITY_IOS
if (Input.touchCount > 0)
{
return Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
}
#endif
return Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
}
LineRenderSystem.cs
This system updates line renderers based on connected stations' positions.
using Unity.Entities;
using Unity.Transforms;
using UnityEngine;
public partial class LineRenderSystem : SystemBase
{
protected override void OnUpdate()
{
Entities.WithAll<LineComponent>().ForEach((Entity entity, ref LineComponent line, in Translation translation) =>
{
// Retrieve positions of connected stations
EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
Translation startTranslation = entityManager.GetComponentData<Translation>(line.StartStation);
Translation endTranslation = entityManager.GetComponentData<Translation>(line.EndStation);
// Update LineRenderer positions
// Assuming LineEntity has a LineRenderer component
var lineRenderer = EntityManager.GetComponentObject<LineRenderer>(entity);
if (lineRenderer != null)
{
lineRenderer.SetPosition(0, startTranslation.Value);
lineRenderer.SetPosition(1, endTranslation.Value);
}
}).WithoutBurst().Run(); // WithoutBurst because of managed code (LineRenderer)
}
}
Note: Managed components like LineRenderer aren’t Burst-compatible, hence WithoutBurst(). For better performance, consider using ECS-specific rendering techniques or Unity’s DOTS graphics API.
- Prefabs Setup
Ensure that both StationPrefab and LinePrefab are configured correctly:
-
StationPrefab:
- Has a
SpriteRenderer component for visual.
- Has
StationComponent via the StationAuthoring script.
- Convert to Entity via
Convert To Entity script with Convert And Inject mode.
-
LinePrefab:
- Has a
LineRenderer component.
- Has
LineComponent via the LineAuthoring script.
- Convert to Entity via
Convert To Entity script with Convert And Inject mode.
Complete Scripts with Annotations
Below is the complete code with detailed comments for clarity.
StationComponent.cs
using Unity.Entities;
using Unity.Mathematics;
/// <summary>
/// Represents a station in the game.
/// </summary>
[GenerateAuthoringComponent]
public struct StationComponent : IComponentData
{
public float2 Position; // Position in world space
}
LineComponent.cs
using Unity.Entities;
using Unity.Mathematics;
/// <summary>
/// Represents a line connecting two stations.
/// </summary>
[GenerateAuthoringComponent]
public struct LineComponent : IComponentData
{
public Entity StartStation; // Starting station entity
public Entity EndStation; // Ending station entity
}
DraggingComponent.cs
using Unity.Entities;
/// <summary>
/// Represents the dragging state during line creation.
/// </summary>
[GenerateAuthoringComponent]
public struct DraggingComponent : IComponentData
{
public Entity FromStation; // The station from which dragging started
}
StationAuthoring.cs
using UnityEngine;
using Unity.Entities;
/// <summary>
/// Authoring component to convert Station GameObject to Entity.
/// </summary>
public class StationAuthoring : MonoBehaviour, IConvertGameObjectToEntity
{
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
Vector3 pos = transform.position;
dstManager.AddComponentData(entity, new StationComponent
{
Position = new float2(pos.x, pos.y)
});
// Optionally, add rendering components if not using Hybrid Renderer
}
}
LineAuthoring.cs
using UnityEngine;
using Unity.Entities;
/// <summary>
/// Authoring component to convert Line GameObject to Entity.
/// </summary>
public class LineAuthoring : MonoBehaviour, IConvertGameObjectToEntity
{
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
dstManager.AddComponentData(entity, new LineComponent
{
StartStation = Entity.Null,
EndStation = Entity.Null
});
// Ensure LineRenderer is properly set up
}
}
InputSystem.cs
using Unity.Entities;
using Unity.Collections;
using Unity.Mathematics;
using UnityEngine;
using Unity.Transforms;
using UnityEngine.InputSystem;
/// <summary>
/// Handles user input for placing stations and connecting lines.
/// Supports both mouse and touch input.
/// </summary>
public partial class InputSystem : SystemBase
{
private BeginInitializationEntityCommandBufferSystem ecbSystem;
private Entity stationPrefab;
private Entity linePrefab;
protected override void OnCreate()
{
base.OnCreate();
ecbSystem = World.GetOrCreateSystem<BeginInitializationEntityCommandBufferSystem>();
}
protected override void OnUpdate()
{
var ecb = ecbSystem.CreateCommandBuffer().AsParallelWriter();
// Initialize prefabs if not yet set
if (stationPrefab == Entity.Null || linePrefab == Entity.Null)
{
Entities.WithAll<StationComponent>().WithoutBurst().ForEach((Entity entity, ref StationComponent station) =>
{
if (stationPrefab == Entity.Null)
{
stationPrefab = entity;
}
}).Run();
Entities.WithAll<LineComponent>().WithoutBurst().ForEach((Entity entity, ref LineComponent line) =>
{
if (linePrefab == Entity.Null)
{
linePrefab = entity;
}
}).Run();
}
// Fetch pointer position
Vector2 pointerPos = GetPointerPosition();
// Start Dragging with Mouse Input
if (Input.GetMouseButtonDown(0))
{
Entities.WithAll<StationComponent>().ForEach((Entity entity, in StationComponent station) =>
{
float distance = math.distance(station.Position, pointerPos);
if (distance <= 0.5f) // Assume station radius is 0.5 units
{
// Add DraggingComponent to mark dragging state
ecb.AddComponent(0, entity, new DraggingComponent { FromStation = entity });
}
}).Run();
}
// Start Dragging with Touch Input
#if UNITY_ANDROID || UNITY_IOS
foreach (var touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
Vector2 touchPos = Camera.main.ScreenToWorldPoint(touch.position);
Entities.WithAll<StationComponent>().ForEach((Entity entity, in StationComponent station) =>
{
float distance = math.distance(station.Position, touchPos);
if (distance <= 0.5f)
{
// Add DraggingComponent
ecb.AddComponent<DraggingComponent>(0, entity, new DraggingComponent { FromStation = entity });
}
}).Run();
}
}
#endif
// Handle Dragging End with Mouse Input
if (Input.GetMouseButtonUp(0))
{
Entities.WithAll<DraggingComponent>().ForEach((Entity draggingEntity, in DraggingComponent dragging) =>
{
// Determine where the pointer was released
Vector2 releasePos = GetPointerPosition();
// Find a station near release position
Entities.WithAll<StationComponent>().ForEach((Entity targetEntity, in StationComponent target) =>
{
float distance = math.distance(target.Position, releasePos);
if (distance <= 0.5f && targetEntity != dragging.FromStation)
{
// Create a line connecting dragging.FromStation and targetEntity
Entity newLine = ecb.Instantiate(0, linePrefab);
ecb.SetComponent(0, newLine, new LineComponent
{
StartStation = dragging.FromStation,
EndStation = targetEntity
});
}
}).Run();
// Remove DraggingComponent to end dragging
ecb.RemoveComponent<DraggingComponent>(0, draggingEntity);
}).Run();
}
// Handle Dragging End with Touch Input
#if UNITY_ANDROID || UNITY_IOS
foreach (var touch in Input.touches)
{
if (touch.phase == TouchPhase.Ended)
{
Vector2 releasePos = Camera.main.ScreenToWorldPoint(touch.position);
Entities.WithAll<DraggingComponent>().ForEach((Entity draggingEntity, in DraggingComponent dragging) =>
{
// Find a station near release position
Entities.WithAll<StationComponent>().ForEach((Entity targetEntity, in StationComponent target) =>
{
float distance = math.distance(target.Position, releasePos);
if (distance <= 0.5f && targetEntity != dragging.FromStation)
{
// Create a line connecting dragging.FromStation and targetEntity
Entity newLine = ecb.Instantiate(0, linePrefab);
ecb.SetComponent(0, newLine, new LineComponent
{
StartStation = dragging.FromStation,
EndStation = targetEntity
});
}
}).Run();
// Remove DraggingComponent
ecb.RemoveComponent<DraggingComponent>(0, draggingEntity);
}).Run();
}
}
#endif
// Handle Station Placement with Mouse (Right-Click)
if (Input.GetMouseButtonDown(1))
{
// Place a new station at pointer position
Entity newStation = ecb.Instantiate(0, stationPrefab);
ecb.SetComponent(0, newStation, new Translation { Value = new float3(pointerPos, 0) });
ecb.SetComponent(0, newStation, new StationComponent { Position = pointerPos });
}
// Handle Station Placement with Touch (Long Press or Double Tap could be implemented)
ecbSystem.AddJobHandleForProducer(Dependency);
}
/// <summary>
/// Retrieves the current pointer position in world coordinates.
/// Supports both mouse and touch.
/// </summary>
/// <returns>Pointer position as Vector2.</returns>
private Vector2 GetPointerPosition()
{
#if UNITY_ANDROID || UNITY_IOS
if (Input.touchCount > 0)
{
return Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
}
#endif
return Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
}
LineRenderSystem.cs
using Unity.Entities;
using Unity.Transforms;
using UnityEngine;
/// <summary>
/// Updates LineRenderers to match connected stations.
/// </summary>
public partial class LineRenderSystem : SystemBase
{
protected override void OnUpdate()
{
Entities.WithAll<LineComponent, Translation>().ForEach((Entity entity, ref LineComponent line, in Translation translation) =>
{
// Retrieve station positions
float3 startPos = float3.zero;
float3 endPos = float3.zero;
bool valid = true;
if (EntityManager.HasComponent<Translation>(line.StartStation))
{
startPos = EntityManager.GetComponentData<Translation>(line.StartStation).Value;
}
else
{
valid = false;
}
if (EntityManager.HasComponent<Translation>(line.EndStation))
{
endPos = EntityManager.GetComponentData<Translation>(line.EndStation).Value;
}
else
{
valid = false;
}
if (!valid) return;
// Update LineRenderer positions
// Since LineRenderer is a managed component, we need to run on the main thread
var lineRenderer = EntityManager.GetComponentObject<LineRenderer>(entity);
if (lineRenderer != null)
{
lineRenderer.positionCount = 2;
lineRenderer.SetPosition(0, startPos);
lineRenderer.SetPosition(1, endPos);
}
}).WithoutBurst().Run(); // Managed components require WithoutBurst
}
}
- Setting Up Prefabs in the Editor
-
StationPrefab:
- Create a 2D Circle sprite.
- Add a
LineRenderer or SpriteRenderer for visualization.
- Add the
StationAuthoring script.
- Add the
ConvertToEntity component, set to Convert And Inject.
- Drag into Assets as
StationPrefab.
-
LinePrefab:
- Create an empty GameObject.
- Add a
LineRenderer component.
- Set material, color, and other properties.
- Add the
LineAuthoring script.
- Add the
ConvertToEntity component, set to Convert And Inject.
- Drag into Assets as
LinePrefab.
Note: Ensure that the LineRenderer in LinePrefab is configured to connect two points.
- Adding Systems to the World
- Ensure that
InputSystem and LineRenderSystem are added to the appropriate system groups (e.g., InitializationSystemGroup, SimulationSystemGroup, etc.). Typically, they can remain in SimulationSystemGroup unless specific ordering is required.
Final Notes
-
Performance Considerations: While this setup uses ECS for data management, the rendering of lines via LineRenderer is still done through GameObjects, which may not fully leverage ECS's performance benefits. For large-scale or highly dynamic line rendering, consider implementing a fully ECS-based rendering solution using Unity’s DOTS Graphics API or leveraging the Hybrid Renderer more effectively.
-
Extensibility: This basic setup can be extended to handle more complex interactions, such as multiple connected lines, station capacities, line colors, and more.
-
Input Enhancements: To enhance user experience, consider adding feedback during dragging (like showing a temporary line), restricting line overlaps, or implementing touch gestures for mobile.
-
Error Handling: Add checks to prevent invalid line creations, such as connecting a station to itself or duplicating existing connections.
-
Testing: Test the game thoroughly on both PC (mouse input) and mobile devices (touch input) to ensure consistent behavior.
By following this guide, you should have a functional foundation for placing stations and connecting lines in a Mini Metro-like game using Unity’s ECS, DOTS, and Burst compiler principles. From here, you can iteratively add more features and optimizations as needed.