Skip to main content

A Complete Guide to Generating Entity Prefabs at Runtime in Unity ECS

Welcome back, everyone! As the title suggests, in this post, we’ll explore how to generate entities from prefabs at runtime. This is a crucial aspect of any game engine, as it allows for the dynamic creation of game objects during gameplay. Since this blog focuses on Unity ECS, I will explain how to generate entities at runtime using this system.

Recap of previous posts: If you haven’t yet checked out the earlier posts, I’ve covered how to create and add components in Unity ECS, as well as the differences between standard components and custom ECS components. I highly recommend reading them, especially if you’re a beginner. In this blog, I will guide you on converting your non-ECS Unity project to Unity ECS and cover all related topics.

I hope you’ve opened your ECS project. In the last couple of posts, I explained how to create entities from the editor, so do check those if you’re unfamiliar with the process. Once you’ve done that, you can start from here.

A Complete Guide to Generating Entity Prefabs at Runtime in Unity ECS

Table of contents 

Transforming the Triangle Game Object into a Prefab for Runtime Instantiation

In the last post, we created the Triangle entity game object in our subscene. Now, let’s turn that Triangle into a prefab and instantiate it at runtime using Unity ECS.

To create a prefab of the Triangle game object, simply select it, then drag and drop it into your Project window. You’ll notice that the Triangle entity will now appear in blue, indicating it’s a prefab.

If you’re having difficulty creating a prefab, I recommend checking Unity’s official documentation on the process of creating prefab. Additionally, if you still find it challenging, refer to the GIF video below for further guidance.

Understanding the Theory: Instantiating Entity Prefabs in Unity ECS

Let’s first recap the standard Unity prefab instantiation process at runtime. In the typical prefab generation system, we must have a prefab and a script that accesses this prefab from the Project window to instantiate it. I assume you’re already familiar with this.

In other words, to instantiate a prefab, we need a script that is responsible for fetching the prefab from storage (the Project folder) and then creating an instance of it in memory at runtime.

The Standard Unity Prefab Instantiation Process: A Quick Recap:

In Unity ECS, we follow a similar process but divide each task into separate sub-processes. Let’s understand this with a real-world example of Unity ECS. In the standard prefab process, we have a script that fetches the prefab from storage (the Project folder), correct? Next, we use that prefab to instantiate it at runtime, correct? This means we have two separate processes for generating a prefab at runtime. I hope you’re following so far, but if not, feel free to leave a comment, and I’ll respond as soon as possible.

The ECS Prefab Instantiation Process: Key Differences and Insights:

Now that we understand these two processes, let’s implement them using Unity’s Entity Component System (ECS).

To access a prefab from storage (the Project folder) in ECS, we use a baking process through a class called a baker. If you’re unfamiliar with this, I recommend checking out my previous post on creating and adding custom components in Unity ECS.

Next, to instantiate it at runtime, ECS provides ISystem and SystemBase interfaces and classes. I’ll explain it in separate post about when to use ISystem and when to use SystemBase, so stay tuned to the LearnUnityECS101 blog. In short, both function similarly to Start, Update, and OnDestroy methods that we’re familiar with from MonoBehaviour.

I hope this helps clarify how to generate entity prefabs at runtime using Unity ECS and the key differences between the standard prefab generation method and the ECS prefab generation method.

If it’s still unclear, don’t worry. In the next section, I’ll implement it in code, and with a live example, you’ll grasp it better.

Implementing Runtime Prefab Generation with Unity ECS: A Step-by-Step Approach:

I personally find reading theory a bit tiring, but it’s important, so we can’t skip it. Let’s approach this section with a positive attitude.

Creating the Required Scripts for Runtime Entity Prefab Instantiation:

As we covered in the theory section, we follow two main processes to generate a prefab: first, accessing the prefab from storage (the Project window), and second, using that prefab to create a copy of the entity in the game scene. Is that clear?
  1. Let’s begin by creating the relevant scripts. To access the prefab entity from storage, we need a MonoBehaviour class. In my case, I’ve created a GeneratePrefab MonoBehaviour class.
  2. To transfer that prefab from MonoBehaviour to the entity world, we must bake it using a baker class. For this, I’ve created a GeneratePrefabAuthoring class that inherits from Baker.
  3. As we know, we need a component to pass MonoBehaviour data to the entity world, so I’ve created a struct named GeneratePrefabStruct.
  4. Finally, we need an update loop to write the prefab generation code that will execute at runtime. For this, I’ve created a class called GeneratePrefabSystem that inherits from ISystem.
  5. In the next section, we’ll write the code to instantiate the entity prefab at runtime in Unity ECS and understand each class and its responsibility.

Code Implementation: Generating Entity Prefabs at Runtime in Unity ECS: 

GeneratePrefab MonoBehaviour: Accessing Prefabs from Storage:

This class contains a public GameObject named "prefab". The GeneratePrefab class is a standard Unity MonoBehaviour class, and to access the prefab from storage, we need a public property to retrieve it. See the code example below.
# Code by learnunityecs101
public class GeneratePrefab : MonoBehaviour
{
    public GameObject prefab;
}

Baking the Prefab: The GeneratePrefabAuthoring Class Explained:

Next, we need a baker class to convert the public properties of the MonoBehaviour into ECS-compatible data. Since Unity handles the baking process automatically, we don’t need to worry about it.

I’ve created a class named GeneratePrefabAuthoring, which inherits from Baker<GeneratePrefab> to implement the abstract baking methods. See the code example below.
# Code by learnunityecs101
public class GeneratePrefabAuthoring : Baker<GeneratePrefab>
{
    public override void Bake(GeneratePrefab authoring)
    {
        var _entity = GetEntity(authoring, TransformUsageFlags.Dynamic);

        AddComponent(_entity, new GeneratePrefabStruct()
        {
            _prefab = GetEntity(authoring.prefab, TransformUsageFlags.Dynamic),
        });
    }
}
Please pay attention here as I’m going to explain how to pass a prefab to an entity. Refer to the code above. I hope you’re familiar with it. In the standard baking process, we usually pass basic data types like int, float, and others, correct? However, in this case, we are passing a GameObject as an entity.

Simply put, if you want to convert a GameObject into an entity, you must use the GetEntity method in the Baker class. This method is responsible for converting a GameObject into an entity. In our example, we’ve created a local variable named _entity to generate an entity for our GeneratePrefab GameObject. Using the AddComponent method, we then pass the prefab as an entity to the component.

If you’re still finding this difficult, I recommend checking out my previous post on creating your first entity and custom component, where I’ve explained the baking process in more detail.

Introducing GeneratePrefabStruct: Structuring Prefab Data for ECS :

Please refer to the code below, which is self-explanatory. I’ve created a public Entity variable named _prefab to store the prefab once it’s been converted to an entity.
# Code by learnunityecs101
public struct GeneratePrefabStruct : IComponentData
{
    public Entity _prefab;
}

Implementing the GeneratePrefabSystem: Using ISystem for Runtime Generation :

Let’s implement the logic to generate the prefab entity at runtime. To accomplish this, we need to use either the ISystem or SystemBase class; in this case, I will be using ISystem.

I have created a public partial struct named GeneratePrefabSystem that inherits from ISystem. The ISystem interface provides us with the OnCreate, OnDestroy, and OnUpdate methods. You can think of OnCreate as the Start method of MonoBehaviour, OnUpdate as the Update method, and OnDestroy as the OnDestroy method of MonoBehaviour.

Instantiating Entities in Unity DOTS: A Practical Code Example: 

Please review the code below and feel free to comment if you have any questions. When I first encountered the instantiation code, I was confused about its purpose, particularly regarding the foreach loop and its performance implications. If you still have similar questions, don’t worry; I will cover these topics in depth in future posts.
# Code by learnunityecs101
public partial struct GeneratePrefabSystem : ISystem
{
    void OnUpdate(ref SystemState state)
    {
        foreach (var _prefab in SystemAPI.Query<RefRW<GeneratePrefabStruct>>())
        {
            var _newPrefab = state.EntityManager.Instantiate(_prefab.ValueRW._prefab);
        }
    }
}

To keep things simple, I don’t want to confuse you further. In standard Unity, we use the GameObject.Instantiate method, correct? Yes, well, in Unity ECS, we have the EntityManager class, which provides us with the Instantiate method. Understood? Good. Please refrain from focusing on how it works or asking other questions for now.

Now, let’s understand the purpose of the foreach loop. If you’re a new visitor and are unfamiliar with it, I’ve mentioned in previous posts that ECS has a world of entities. Here, "world" refers to a list of all entities. What do you do when you have a list and want to retrieve specific data from it? You use a loop, correct? That’s why we’re employing the foreach loop here.

Next, let’s understand how to access the ECS world I mentioned earlier. To do this, you need queries to find your entities within it. To simplify this process, Unity provides us with the SystemAPI class, which contains the Query method. Just remember to keep it simple and not focus on the intricacies.

So, what would you do if you wanted to find GeneratePrefabStruct? You would pass that struct into the query, correct? Yes, good! Unity gives us two options to access that struct: you can either use your data as read-only or gain full access to it. Thus, Unity offers two options: RefRW and RefRO. As the names suggest, RefRW means a reference with read and write access, while RefRO means read-only access. check below gif how it will look after play.


I hope you understand the above context. Now we have a query to find GeneratePrefabStruct, and we have a method to instantiate it, which means the goal of this post—to provide a complete guide on generating entity prefabs at runtime in Unity ECS—has been achieved.

Summarising the Process: Generating Entity Prefabs at Runtime in Unity ECS :

In Unity ECS, generating entity prefabs at runtime involves using the EntityManager class and its Instantiate method, which replaces the standard GameObject.Instantiate method. A foreach loop is employed to iterate through the list of entities in the ECS world. To access entities, queries are used, facilitated by the SystemAPI class and its Query method. When looking for a specific struct, such as GeneratePrefabStruct, developers can choose between read-only or full access options using RefRO and RefRW, respectively. This guide aims to provide a comprehensive understanding of the process of generating entity prefabs in Unity ECS. 

Comments

Popular posts from this blog

What is ECS in Unity ?

Today, I will address common questions asked by Unity developers: 'What is ECS in Unity?', 'Is ECS worth using in your next project?', 'Can I convert my old project to Unity ECS?', and 'Where should I start learning Unity ECS?'. Stay with me as I cover all these answers in this post. Welcome back! If you're not aware of why I created this blog, let me clarify. I'm converting an old Unity project to the new DOTS technologies. First, I’ll be using ECS to re-architect the project, and then I’ll delve into the physics aspects. Stay with me and enhance your skills by learning Unity ECS. When I began learning Unity DOTS, I noticed several frequently asked questions and discussions posted on Reddit, Unity forums, and Unity Discord channels. Let me share my experiences and answer these questions. Table of Content : What is ECS in Unity? What is Entity ? What is Component ? What is System ? Is ECS worth using in your next projec

Setting Up Unity DOTS: Creating and Configuring Your First Entity

Welcome back, Unity developers! Today, I will be setting up a non-ECS Unity project to run using the Entity Component System (ECS), Moreover you will setup your first subscene and create your first entity. I will address entity not visible issue. If you haven't yet checked the commonly asked questions about the Entity Component System , you should take a look first, where I've explained the basic definition of ECS in Unity. Setting Up Unity DOTS Creating and Configuring Your First Entity by LearnUnityECS101.Blogspot.com Table of Contents : Project Clone Instruction ECS Package Install and Setup Guide Setup ECS Scene Create Your First Entity Entity is not visible error Verify Your First Entity   Domain Reload Setting   Summarizing Project Clone Instruction: First of all, you need a Unity project in working condition. If you already have such a project, you can use it, but I would recommend using the project I am about to convert to Unity DOTS - ECS. Ple

Creating and Adding Components in Unity ECS: A Step-by-Step Guide

Welcome to our guide on creating and adding components in Unity using ECS (Entity Component System). In this post, we’ll explore the differences between Unity's standard components and ECS components, and walk you through the process of adding components to entities. We’ll cover key concepts like baking, and demonstrate how to set up and view components in both authoring and runtime modes. By the end of this tutorial, you'll have a clear understanding of how to work with ECS components and implement them in your Unity projects. Let me remind you of the full form of ECS: Entity Component System. It consists of three key elements: 1. Entity, 2. Component, and 3. System. In this blog post, I will specifically focus on how to create and add components, and explain the differences between Unity's standard components and ECS components. If you haven’t already, be sure to check out my blog post on  creating your first entity and setting up a subscene