IComponentData
- Game Development course
- Expert
- Lesson 21/47
- 4 min
Learn to define components with IComponentData.
What Is IComponentData?
IComponentData is an interface used to create data components in Unity ECS architecture. Structures implementing this interface are generally defined as structs and are used to add data to Entity objects. For example, a Position component can store an object's coordinates.
using Unity.Entities;
public struct Position : IComponentData
{
public float X;
public float Y;
}This component only stores data; the logic that processes the data belongs in a separate System.
Creating a Data Component
To create an ECS component, include the Unity.Entities namespace in your project. Then define a struct that implements the IComponentData interface. You can place numerical data belonging to a game object inside the component.
using Unity.Entities;
public struct Health : IComponentData
{
public int Value;
}The Health component can be used to store the health value of an Entity object.
Practice Create a Score Component
Create an ECS component named Score. The structure must implement the IComponentData interface and contain an int field named Value. Also include the required Unity.Entities namespace and define a static method that prints the initial score to the console.
Starter code
// Score veri bileşenini tanımla
// IComponentData arayüzünü uygula
// Value alanını ekle
// Başlangıç skorunu yazdıran metodu tanımlaSample solution
using Unity.Entities;
using UnityEngine;
public struct Score : IComponentData
{
public int Value;
public static void PrintInitial()
{
Debug.Log("Score: " + 0);
}
}Expected output
Score: 0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which C# type is used when creating an ECS data component?
- delegate
- struct Correct answer
- enum
- interface
Explanation: ECS data components implementing IComponentData are defined as structs.
2 Complete the Health Component
public struct Health : ____
{
public int Value;
}
public struct Health : IComponentData
{
public int Value;
}
Explanation: IComponentData allows the Health structure to be used as an ECS data component.
3 IComponentData Structure
| Term | Meaning |
|---|---|
IComponentData |
ECS component interface |
struct |
Defines a value-type structure |
int Value |
Stores integer data |
Unity.Entities |
Contains ECS types |