User: I'm looking at making a Mini Metro clone in Unity using ECS principles and DOTS/Burst. It is a 2D game. I want to start by just making the simplest functionality: placing a station and connecting a line between them. The station will be a circle that the user can place, and the line connects two stations. The user must click on a station, drag from it to the next station then release. I want to support both mouse functionality on PC and touch functionality on mobile. Explain everything thoroughly.
Assistant
Creating a Mini Metro clone using Unity’s Entity Component System (ECS) principles, Data-Oriented Technology Stack (DOTS), and Burst Compiler is an excellent way to leverage high-performance, scalable code suitable for both PC and mobile platforms. Below is a comprehensive guide to help you implement the simplest functionality of placing stations and connecting lines between them in a 2D environment.
Table of Contents
Introduction to ECS, DOTS, and Burst
Setting Up Your Unity Project
Designing the Data Model
Implementing User Input Handling
Creating Systems for Station and Line Management
Rendering Stations and Lines
Handling Mouse and Touch Inputs Simultaneously
Testing and Optimization
Conclusion and Next Steps
1. Introduction to ECS, DOTS, and Burst
Entity Component System (ECS): A design pattern that emphasizes data-oriented design, separating data (components) from behavior (systems). It promotes cache-friendly data layouts and parallel processing.
Data-Oriented Technology Stack (DOTS): A collection of Unity packages designed for high-performance code. It includes ECS, the C# Job System, and the Burst Compiler.
Burst Compiler: A compiler that translates your C# jobs into highly optimized native code, significantly improving performance.
Benefits:
Performance: Efficient CPU usage, making it ideal for games with numerous objects.
Scalability: Easily handles increasing numbers of entities.
Maintainability: Clear separation of data and behavior promotes cleaner codebases.
Install the Latest Unity Version: Ensure you have a version that supports the latest DOTS packages (preferably Unity 2023.x or later).
2.2. Create a New 2D Project
Open Unity Hub.
Click on "New Project".
Select the "2D" template.
Name your project (e.g., MiniMetroClone) and choose a save location.
Click "Create".
2.3. Install Required Packages
Open your project in Unity.
Go to Window > Package Manager.
Switch "Packages" to "Unity Registry".
Install the following packages:
Entities: Core package for ECS.
Hybrid Renderer 2D: For rendering ECS entities in 2D.
Burst: For compiling high-performance jobs.
Mathematics: For optimized math operations.
Note: Depending on the Unity version, some packages might have dependencies or specific versions. Ensure compatibility by checking the package documentation.
2.4. Enable Necessary Project Settings
Scripting Backend: Ensure that the Scripting Backend is set to IL2CPP for better Burst compatibility.
Go to Edit > Project Settings > Player > Other Settings.
Under Configuration, set Scripting Backend to IL2CPP.
Enable Burst Compilation:
Burst is usually enabled by default once the package is installed, but verify in Burst AOT Settings if necessary.
3. Designing the Data Model
In ECS, entities are “empty” containers that hold components, which are pure data structures. Systems operate on entities with specific components.
3.1. Define Components
Station Component
Represents a station entity in the game.
csharp
using Unity.Entities;
using Unity.Mathematics;
public struct Station : IComponentData
{
public float2 Position; // 2D position of the station
public float Radius; // Radius for rendering and hit detection
}
Line Component
Represents a connection (line) between two stations.
csharp
using Unity.Entities;
public struct Line : IComponentData
{
public Entity StartStation; // Reference to the starting station
public Entity EndStation; // Reference to the ending station
}
SelectedStation Component
Markers for UI interaction, indicating a station is currently selected.
csharp
using Unity.Entities;
public struct SelectedStation : IComponentData
{
// No data needed; the presence of this component marks selection
}
3.2. Define Entity Archetypes
While setting up systems, you’ll define archetypes implicitly based on the components your systems query. For simplicity, we'll focus on adding components when creating entities.
4. Implementing User Input Handling
Handling both mouse and touch inputs requires abstraction to handle PC and mobile interactions seamlessly.
4.1. Input Detection System
Create a system that detects input events and translates them into actions within ECS.
csharp
using Unity.Entities;
using Unity.Transforms;
using UnityEngine;
using Unity.Mathematics;
using Unity.Collections;
using Unity.Jobs;
public partial class InputSystem : SystemBase
{
protected override void OnUpdate()
{
bool isTouchSupported = Input.touchSupported;
bool isClicked = false;
float2 inputPosition = float2.zero;
if (isTouchSupported && Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Ended)
{
inputPosition = Camera.main.ScreenToWorldPoint(touch.position);
isClicked = true;
}
}
else
{
if (Input.GetMouseButtonDown(0) || Input.GetMouseButton(0) || Input.GetMouseButtonUp(0))
{
inputPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
isClicked = true;
}
}
if (isClicked)
{
// Create a command to handle input
// Use a singleton buffer or a command entity to pass input to other systems
EntityCommandBuffer ecb = new EntityCommandBuffer(Unity.Collections.Allocator.TempJob);
Entity inputEntity = ecb.CreateEntity();
ecb.AddComponent(inputEntity, new InputComponent
{
Position = inputPosition,
ButtonState = isTouchSupported ?
(Input.GetTouch(0).phase == TouchPhase.Ended ? ButtonState.Released : ButtonState.Pressed)
:
(Input.GetMouseButtonUp(0) ? ButtonState.Released : ButtonState.Pressed)
});
ecb.Playback(EntityManager);
ecb.Dispose();
}
}
}
public struct InputComponent : IComponentData
{
public float2 Position;
public ButtonState ButtonState;
}
public enum ButtonState
{
Pressed,
Released
}
Note: In a production environment, you might want to separate touch and mouse inputs more carefully, especially handling multiple touches, but for simplicity, this example focuses on single-touch and mouse inputs.
4.2. Processing Input
Another system will process the InputComponent and perform actions like selecting stations or creating lines.
csharp
using Unity.Entities;
using Unity.Transforms;
using Unity.Mathematics;
using Unity.Collections;
using Unity.Jobs;
public partial class InputProcessingSystem : SystemBase
{
protected override void OnUpdate()
{
Entities.WithoutBurst().ForEach((Entity inputEntity, in InputComponent input) =>
{
if (input.ButtonState == ButtonState.Pressed)
{
// Handle selection or dragging
// Check if a station is clicked
Entities.WithoutBurst().ForEach((Entity stationEntity, in Station station) =>
{
float distance = math.distance(station.Position, input.Position);
if (distance <= station.Radius)
{
// Mark this station as selected
// Remove existing SelectedStation components
Entities.WithAll<SelectedStation>().ForEach((Entity selectedEntity) =>
{
EntityManager.RemoveComponent<SelectedStation>(selectedEntity);
}).Run();
// Add SelectedStation component
EntityManager.AddComponent<SelectedStation>(stationEntity);
}
}).Run();
}
else if (input.ButtonState == ButtonState.Released)
{
// Handle line creation if a station is already selected
Entity selectedStation = Entity.Null;
Entities.WithAll<SelectedStation>().ForEach((Entity entity) =>
{
selectedStation = entity;
}).Run();
if (selectedStation != Entity.Null)
{
// Find if release is on another station
Entities.WithoutBurst().ForEach((Entity stationEntity, in Station station) =>
{
float distance = math.distance(station.Position, input.Position);
if (distance <= station.Radius && stationEntity != selectedStation)
{
// Create a line between selectedStation and stationEntity
Entity lineEntity = EntityManager.CreateEntity();
EntityManager.AddComponentData(lineEntity, new Line
{
StartStation = selectedStation,
EndStation = stationEntity
});
// Remove SelectedStation component
EntityManager.RemoveComponent<SelectedStation>(selectedStation);
}
}).Run();
}
}
// Remove the input entity after processing
EntityManager.DestroyEntity(inputEntity);
}).Run();
}
}
Note: The above example uses .Run() for simplicity and immediate execution. For better performance, especially with Burst, you should use proper job scheduling and consider thread safety.
5. Creating Systems for Station and Line Management
5.1. Station Placement System
This system allows players to place stations by tapping/clicking on empty space.
csharp
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;
public partial class StationPlacementSystem : SystemBase
{
protected override void OnUpdate()
{
// Assuming you have an input to place station, e.g., a separate input component or key press
// For simplicity, integrating with InputSystem is recommended
}
// Integration might be similar to InputProcessingSystem
// Optionally, handle double-click or a specific input to place a station
}
Implementation Note: For this initial functionality, we might omit this system and assume stations are placed manually in the scene or add a simple button to place stations. Alternatively, integrate station placement within InputProcessingSystem.
5.2. Line Management System
This system manages the creation and rendering of lines between stations.
Creating Mesh or LineRenderer Entities:
Since ECS focuses on data, you might need to create Hybrid Renderer entities for the lines.
csharp
using Unity.Entities;
using Unity.Transforms;
using Unity.Rendering;
using Unity.Mathematics;
using UnityEngine;
public partial class LineRenderingSystem : SystemBase
{
protected override void OnUpdate()
{
// Handle rendering lines based on Line components
Entities.WithoutBurst().ForEach((Entity lineEntity, ref Line line) =>
{
// Create a GameObject with LineRenderer if not already created
if (!EntityManager.HasComponent<LineRendererComponent>(lineEntity))
{
// Convert to GameObject if necessary or use rendering via Hybrid Renderer
// For simplicity, using GameObject conversion is easier but less performant
}
}).Run();
}
}
Implementation Note: Handling rendering in ECS can be complex. Using Hybrid Renderer 2D or converting to dedicated GameObjects might be necessary for visualizing lines.
6. Rendering Stations and Lines
6.1. Using Hybrid Renderer 2D
Hybrid Renderer allows ECS entities to be rendered using Unity’s rendering systems. For 2D, ensure you have the Hybrid Renderer 2D package installed.
6.2. Creating Entities with Render Components
When creating Station and Line entities, add rendering components.
Station Rendering
csharp
using Unity.Entities;
using Unity.Transforms;
using Unity.Rendering;
using UnityEngine;
public class StationAuthoring : MonoBehaviour
{
// MonoBehaviour not strictly necessary but useful for authorship
}
public class StationBaker : Baker<StationAuthoring>
{
public override void Bake(StationAuthoring authoring)
{
var entity = GetEntity(TransformUsageFlags.Dynamic);
AddComponent(entity, new Station
{
Position = (float2)authoring.transform.position,
Radius = 1.0f // Example radius
});
// Add Sprite Renderer component
AddComponent(entity, new RenderMesh2D
{
// Assign appropriate sprite
// Asset references need to be handled
});
}
}
Note: Use Baker classes (introduced in newer Unity ECS versions) to convert MonoBehaviours to ECS entities. Alternatively, use pure ECS code.
Line Rendering
Lines can be rendered using LineRenderer or via ECS-compatible rendering components.
csharp
using Unity.Entities;
using Unity.Rendering;
using Unity.Mathematics;
public struct LineRender : IComponentData
{
public float2 StartPos;
public float2 EndPos;
public float Thickness;
public Color Color;
}
Then, create a system that updates LineRender components based on Line component data.
6.3. Updating Render Data
csharp
using Unity.Entities;
using Unity.Transforms;
using Unity.Mathematics;
public partial class LineRenderUpdateSystem : SystemBase
{
protected override void OnUpdate()
{
Entities.ForEach((ref LineRender lineRender, in Line line, in Station startStation, in Station endStation) =>
{
lineRender.StartPos = startStation.Position;
lineRender.EndPos = endStation.Position;
// Update other properties if necessary
}).ScheduleParallel();
}
}
7. Handling Mouse and Touch Inputs Simultaneously
To ensure both mouse and touch inputs work seamlessly, abstract the input handling.
7.1. Input Abstraction
Create a unified input abstraction that processes both input types and outputs a standardized format for the rest of the systems.
csharp
public struct UnifiedInput
{
public float2 Position;
public InputType Type;
}
public enum InputType
{
Mouse,
Touch
}
Update the InputSystem to emit UnifiedInput instead of separate data types.
7.2. Processing Unified Inputs
Modify InputProcessingSystem to handle UnifiedInput components accordingly, differentiating between mouse and touch if necessary.
8. Testing and Optimization
8.1. Testing Functionality
Station Placement:
Ensure stations are placed accurately where the user clicks/touches.
Verify that stations are rendered correctly.
Line Connection:
Click/touch a station, drag to another station, and release.
Confirm that a line connects the two stations.
Input Compatibility:
Test on both PC (mouse) and mobile (touch) to ensure inputs work as expected.
8.2. Optimization with Burst and Jobs
Burst Compilation:
Ensure your systems are compatible with Burst by marking them with [BurstCompile] where applicable.
Job Scheduling:
Use parallel jobs for systems that can run concurrently to maximize performance.
Memory Layout:
Optimize component data to be cache-friendly. For example, use float2 instead of separate float fields for positions.
9. Conclusion and Next Steps
By following the steps outlined above, you can create the foundational functionality of a Mini Metro clone using Unity’s ECS, DOTS, and Burst. Here’s a summary and suggestions for further development:
Summary:
Set up Unity with necessary DOTS packages.
Designed data models using components and entities.
Implemented unified input handling for mouse and touch.
Created systems to manage station selection and line creation.
Utilized Hybrid Renderer 2D for visualizing stations and lines.
Next Steps:
Enhance Rendering:
Implement dynamic line rendering that updates in real-time as stations move or lines are added.
Add visual feedback for selected stations.
Add Station Types:
Differentiate stations with various attributes or functionalities.
Implement Pathfinding:
Allow lines to follow grid-based paths or curves for a more visually appealing network.
UI Enhancements:
Add buttons for station placement mode, undo actions, or displaying information.
Persistency:
Save and load station and line data to preserve game state.
Performance Profiling:
Use Unity’s Profiler to identify and optimize any performance bottlenecks.
Expand Input Handling:
Support multi-touch gestures or more complex interactions as your game grows.
By leveraging ECS, DOTS, and Burst, your Mini Metro clone will benefit from high performance and scalability, making it robust for both current needs and future expansions.