Game Development
Challenge 2: ECS component
Write a component struct derived from IComponentData.
What is IComponentData?
In the ECS architecture components hold only data; game logic lives in systems. A component is defined with a struct that implements the IComponentData interface; a value type is used instead of a class because data is stored more efficiently this way. Inside a component only fields are found, never methods.
public struct HareketBileseni : IComponentData
{
public float hiz;
}
The component above carries only the hiz data.
Exercise Movement component
Define a data component named HareketBileseni with a hiz field; the component should be a structure that implements the IComponentData interface. In the Start method of the class BilesenTest, create a variable of that type, assign the value 5f to its hiz field and print the text "Hiz: " joined with the hiz field using Debug.Log.
Show example solution
using Unity.Entities;
using UnityEngine;
public struct HareketBileseni : IComponentData
{
public float hiz;
}
public class BilesenTest : MonoBehaviour
{
void Start()
{
HareketBileseni h = new HareketBileseni();
h.hiz = 5f;
Debug.Log("Hiz: " + h.hiz);
}
}
Exercise Health component
Define a data component named YasamBileseni with a can field; the component should be a structure that implements the IComponentData interface. In the Start method of the class YasamTest, create a variable of that type, assign the value 50 to its can field and print the text "Can: " joined with the can field using Debug.Log.
Show example solution
using Unity.Entities;
using UnityEngine;
public struct YasamBileseni : IComponentData
{
public int can;
}
public class YasamTest : MonoBehaviour
{
void Start()
{
YasamBileseni y = new YasamBileseni();
y.can = 50;
Debug.Log("Can: " + y.can);
}
}
Test yourself
-
With which keyword is an IComponentData derived data component defined?
- With enum
- With struct
- With class
- With interface
Show answer
With struct — ECS components are defined with the value type struct; struct is used instead of class.
-
Define the component
public ____ HareketBileseni : IComponentData
Show answer
public struct HareketBileseni : IComponentData
-
ECS component terms
- IComponentData
- The interface that defines a component
- Bileşen
- A structure that holds only data
- Entity
- The identity that components attach to
- Alan
- The data record inside a component
Next lesson: Challenge 3: Editor menu