DOTS NetCode and Prefabs
Code and workflows to turn asteroid entity prefabs into NetCode "ghosts"

What you'll develop on this page

Asteroid prefab server spawning and destroying
We will update our Asteroid prefab, effectively "turning it into" a NetCode ghost so that spawning and destroying are handled by the server.

Asteroids spawn and movement

First, some background:

NetCode refers to networked entities as "Ghosts" πŸ‘». Ghosts must be declared before runtime, there is no way to currently update our ghost list from inside a system; it must be done through authoring.
Add a "GhostAuthoringComponent" to the prefabs (this is a special NetCode component). You can think of this as "registering" our Asteroid, Player, and Bullet prefab.

Ghost snapshots

A ghost is a networked object that the server simulates. During every frame, the server sends a snapshot of the current state of all ghosts to the client. The client presents them, but cannot directly control or affect them because the server owns them.
The ghost snapshot system synchronizes entities which exist on the server to all clients. To make it perform properly, the server processes per ECS chunk rather than per entity. On the receiving side the processing is done per entity. This is because it is not possible to process per chunk on both sides, and the server has more connections than clients.

Ghost authoring component

The ghost authoring component is based on specifying ghosts as Prefabs with the GhostAuthoringComponent on them. The GhostAuthoringComponent has a small editor which you can use to configure how NetCode synchronizes the Prefab.
​
Ghost Authoring Component
You must set the Name, Importance, Supported Ghost Mode, Default Ghost Mode and Optimization Mode property on each ghost. Unity uses the Importance property to control which entities are sent when there is not enough bandwidth to send all. A higher value makes it more likely that the ghost will be sent.
You can select from three different Supported Ghost Mode types:
    All - this ghost supports both being interpolated and predicted.
    Interpolated - this ghost only supports being interpolated, it cannot be spawned as a predicted ghost.
    Predicted - this ghost only supports being predicted, it cannot be spawned as a interpolated ghost.
You can select from three different Default Ghost Mode types:
    Interpolated - all ghosts Unity receives from the server are treated as interpolated.
    Predicted - all ghosts Unity receives from the server are treated as predicted.
    Owner predicted - the ghost is predicted for the client that owns it, and interpolated for all other clients. When you select this property, you must also add a GhostOwnerComponent and set its NetworkId field in your code. Unity compares this field to each clients’ network ID to find the correct owner.
You can select from two different Optimization Mode types:
    Dynamic - the ghost will be optimized for having small snapshot size both when changing and when not changing.
    Static - the ghost will not be optimized for having small snapshot size when changing, but it will not be sent at all when it is not changing.
To override the default client instantiation you can create a classification system updating after ClientSimulationSystemGroup and before GhostSpawnClassificationSystem which goes through the GhostSpawnBuffer buffer on the singleton entity with GhostSpawnQueueComponent and change the SpawnType.
Unity uses attributes in C# to configure which components and fields are synchronized as part of a ghost. You can see the current configuration in the GhostAuthoringComponent by selecting Update component list, but you cannot modify it from the inspector.
To change which versions of a Prefab a component is available on you use PrefabType in a GhostComponentAttribute on the component. PrefabType can be on of the these types:
    InterpolatedClient - the component is only available on clients where the ghost is interpolated.
    PredictedClient - the component is only available on clients where the ghost is predicted.
    Client - the component is only available on the clients, both when the ghost is predicted and interpolated.
    Server - the component is only available on the server.
    AllPredicted - the component is only available on the server and on clients where the ghost is predicted.
    All - the component is available on the server and all clients.
For example, if you add [GhostComponent(PrefabType=GhostPrefabType.Client)] to RenderMesh, the ghost won’t have a RenderMesh when it is instantiated on the server, but it will have it when instantiated on the client.
A component can set OwnerPredictedSendType in the GhostComponentAttribute to control which clients the component is sent to when it is owner predicted. The available modes are:
    Interpolated - the component is only sent to clients which are interpolating the ghost.
    Predicted - the component is only sent to clients which are predicting the ghost.
    Interpolated - the component is sent to all clients.
If a component is not sent to a client NetCode will not modify the component on the client which did not receive it.
A component can also set SendDataForChildEntity to true or false in order to control if the component it sent when it is part of a child entity of a ghost with multiple entities.
For each component, you need to add an attribute to the values you want to sent. Add a [GhostField] attribute to the fields you want to send in an IComponentData. The GhostFieldAttribute can specify Quantization for floating point numbers. The floating point number will be multiplied by this number and converted to an integer in order to save bandwidth. Specifying a Quantization is mandatory for floating point numbers and not supported for integer numbers. To send a floating point number unquantized you have to explicitly specify [GhostField(Quantization=0)]. The GhostFieldAttribute also has a Interpolate property which controls if the field will be interpolated or not on clients which are not predicting the ghost. Finally the GhostFieldAttribute has a SubType property which can be set to an integer value to use special serialization rules supplied by the game for that specific field.
As well as adding attributes, you can specify rules for components which you do not have source access to by creating an assembly with a name ending with .NetCodeGen. This assembly should contain a class implementing the interface IGhostDefaultOverridesModifier. Implement the method public void Modify(Dictionary<string, GhostAuthoringComponentEditor.GhostComponent> overrides) and add an entry to the ictionary with the full name of the component as key and a value containing the desired override attributes.

Entity spawning

When the client side receives a new ghost, the ghost type is determined by a set of classification systems and then a spawn system spawns it. There is no specific spawn message, and when the client receives an unknown ghost ID, it counts as an implicit spawn.
Because the client interpolates snapshot data, Unity cannot spawn entities immediately, unless it was preemptively spawned, such as with spawn prediction. This is because the data is not ready for the client to interpolate it. Otherwise, the object would appear and then not get any more updates until the interpolation is ready.
Therefore normal spawns happen in a delayed manner. Spawning is split into three main types as follows:
    Delayed or interpolated spawning (Asteroids Prefab). The entity is spawned when the interpolation system is ready to apply updates. This is how remote entities are handled, because they are interpolated in a straightforward manner.
    Predicted spawning for the client predicted player object (Player Prefab). The object is predicted so the input handling applies immediately. Therefore, it doesn't need to be delay spawned. While the snapshot data for this object arrives, the update system applies the data directly to the object and then plays back the local inputs which have happened since that time, and corrects mistakes in the prediction.
    Predicted spawning for player spawned objects (Bullet Prefab). These are objects that the player input spawns, like in-game bullets or rockets that the player fires. The spawn code needs to run on the client, in the client prediction system. Spawn the predicted client version of the ghost prefab and add a PredictedGhostSpawnRequestComponent. Then when the first snapshot update for the entity arrives it will apply to that predict spawned object (no new entity is created). After this, the snapshot updates are applied the same as in the predicted spawning for client predicted player object model.
You need to implement some specific code to handle the predicted spawning for player spawned objects. You need to create a system updating in the ClientSimulationSystemGroup after GhostSpawnClassificationSystem. The system needs to go through the GhostSpawnBuffer buffer stored on a singleton with a GhostSpawnQueueComponent. For each entry in that list it should compare to the entries in the PredictedGhostSpawn buffer on the singleton with a PredictedGhostSpawnList component. If the two entries are the same the classification system should set the PredictedSpawnEntity property in the GhostSpawnBuffer and remove the entry from GhostSpawnBuffer.
NetCode spawns entities on the client with a Prefab stored in the GhostPrefabCollectionComponent singleton.
Prefabs in parenthesis in spawning types added my Moetsi
From the 3 types of spawning described in the section above, asteroids are delayed, interpolated, or spawning (re-read the section above if you missed it). The server will spawn the asteroids, and when the interpolation system is ready to apply updates, the client will then spawn them as well.
To the client, asteroids just "appear" (because NetCode syncs ghosted entities) and their movement is updated through Snapshots.
The client is not running any Physics code for the asteroid movement; the asteroids will move because of updated snapshots from the server. The server runs the systems that take in the PhysicsVelocity and updates the asteroids positions, these updates are then sent to the clients.
If it sounds like we are being repetitive, we are. It is important to understand the concept of interpolated ghosts to make sense of our implementations πŸ’ͺ.
If the concepts 'interpolated spawning' and 'predicted spawning' are making your head spin, read and watch the explainer content we provided in the "Overview" page of this DOTS NetCode section.

Now, let's implement:

    Select the Asteroid prefab and add a GhostAuthoringComponent. Fill out the following fields:
      Name = "Asteroid"
      Importance = "100"
      Supported Ghost Modes = All
      Default Ghost Mode = Interpolated
      Optimization Mode = Dynamic
    Click "Update component list" to see the components that will be ghosted
      You may get an error which you can ignore
      The list of components that appear have a marker S/IC/PC
        This stands for:
          "Server" (the component is only available on the server)
          "Interpolated Client" (the component is only available on clients where the ghost is interpolated)
          "Predicted Client" (the component is only available on clients where the ghost is predicted)
        You might be curious why there is a "RenderMesh" component, yet rendering is not needed on the server (because, as we know, the server does not have a presentation layer system). This is just because NetCode is having a tough time excluding meshes automatically (but this will be updated in future releases!)
      When we add the GhostAuthoringComponent to our Player prefab and our Bullet prefab we will see how these values change
      At the bottom of the component list you'll find the Rotation and Translation components. Expand these components:
        Here you can see different fields configured for quantization and interpolation
      You can in the Inspector override default values for components and where they get sent
        This is newly introduced in NetCode v0.6
          NetCode v0.6 provided a lot of awesome updates that allows us to change what data gets sent where
If any of the fields above are confusing, check out the background information above or read it straight from the source in NetCode's Ghost snapshots documentation​
We need to update the systems that interacted with asteroids. Let's start with AsteroidSpawnSystem.
    Find AsteroidSpawnSystem and replace the current code with the code snippet below:
1
using System.Diagnostics;
2
using Unity.Entities;
3
using Unity.Collections;
4
using Unity.Jobs;
5
using Unity.Mathematics;
6
using Unity.Transforms;
7
using UnityEngine;
8
using Unity.Burst;
9
using Unity.Physics;
10
using Unity.NetCode;
11
​
12
//Asteroid spawning will occur on the server
13
[UpdateInGroup(typeof(ServerSimulationSystemGroup))]
14
public class AsteroidSpawnSystem : SystemBase
15
{
16
//This will be our query for Asteroids
17
private EntityQuery m_AsteroidQuery;
18
​
19
//We will use the BeginSimulationEntityCommandBufferSystem for our structural changes
20
private BeginSimulationEntityCommandBufferSystem m_BeginSimECB;
21
​
22
//This will be our query to find GameSettingsComponent data to know how many and where to spawn Asteroids
23
private EntityQuery m_GameSettingsQuery;
24
​
25
//This will save our Asteroid prefab to be used to spawn Asteroids
26
private Entity m_Prefab;
27
​
28
//This is the query for checking network connections with clients
29
private EntityQuery m_ConnectionGroup;
30
​
31
protected override void OnCreate()
32
{
33
//This is an EntityQuery for our Asteroids, they must have an AsteroidTag
34
m_AsteroidQuery = GetEntityQuery(ComponentType.ReadWrite<AsteroidTag>());
35
​
36
//This will grab the BeginSimulationEntityCommandBuffer system to be used in OnUpdate
37
m_BeginSimECB = World.GetOrCreateSystem<BeginSimulationEntityCommandBufferSystem>();
38
​
39
//This is an EntityQuery for the GameSettingsComponent which will drive how many Asteroids we spawn
40
m_GameSettingsQuery = GetEntityQuery(ComponentType.ReadWrite<GameSettingsComponent>());
41
​
42
//This says "do not go to the OnUpdate method until an entity exists that meets this query"
43
//We are using GameObjectConversion to create our GameSettingsComponent so we need to make sure
44
//The conversion process is complete before continuing
45
RequireForUpdate(m_GameSettingsQuery);
46
​
47
//This will be used to check how many connected clients there are
48
//If there are no connected clients the server will not spawn asteroids to save CPU
49
m_ConnectionGroup = GetEntityQuery(ComponentType.ReadWrite<NetworkStreamConnection>());
50
}
51
52
protected override void OnUpdate()
53
{
54
//Here we check the amount of connected clients
55
if (m_ConnectionGroup.IsEmptyIgnoreFilter)
56
{
57
// No connected players, just destroy all asteroids to save CPU
58
EntityManager.DestroyEntity(m_AsteroidQuery);
59
return;
60
}
61
​
62
//Here we set the prefab we will use
63
if (m_Prefab == Entity.Null)
64
{
65
//We grab the converted PrefabCollection Entity's AsteroidAuthoringComponent
66
//and set m_Prefab to its Prefab value
67
m_Prefab = GetSingleton<AsteroidAuthoringComponent>().Prefab;
68
//we must "return" after setting this prefab because if we were to continue into the Job
69
//we would run into errors because the variable was JUST set (ECS funny business)
70
//comment out return and see the error
71
return;
72
}
73
​
74
//Because of how ECS works we must declare local variables that will be used within the job
75
//You cannot "GetSingleton<GameSettingsComponent>()" from within the job, must be declared outside
76
var settings = GetSingleton<GameSettingsComponent>();
77
​
78
//Here we create our commandBuffer where we will "record" our structural changes (creating an Asteroid)
79
var commandBuffer = m_BeginSimECB.CreateCommandBuffer();
80
​
81
//This provides the current amount of Asteroids in the EntityQuery
82
var count = m_AsteroidQuery.CalculateEntityCountWithoutFiltering();
83
​
84
//We must declare our prefab as a local variable (ECS funny business)
85
var asteroidPrefab = m_Prefab;
86
​
87
//We will use this to generate random positions
88
var rand = new Unity.Mathematics.Random((uint)Stopwatch.GetTimestamp());
89
​
90
Job
91
.WithCode(() => {
92
for (int i = count; i < settings.numAsteroids; ++i)
93
{
94
// this is how much within perimeter asteroids start
95
var padding = 0.1f;
96
​
97
// we are going to have the asteroids start on the perimeter of the level
98
// choose the x, y, z coordinate of perimeter
99
// so the x value must be from negative levelWidth/2 to positive levelWidth/2 (within padding)
100
var xPosition = rand.NextFloat(-1f*((settings.levelWidth)/2-padding), (settings.levelWidth)/2-padding);
101
// so the y value must be from negative levelHeight/2 to positive levelHeight/2 (within padding)
102
var yPosition = rand.NextFloat(-1f*((settings.levelHeight)/2-padding), (settings.levelHeight)/2-padding);
103
// so the z value must be from negative levelDepth/2 to positive levelDepth/2 (within padding)
104
var zPosition = rand.NextFloat(-1f*((settings.levelDepth)/2-padding), (settings.levelDepth)/2-padding);
105
106
//We now have xPosition, yPostiion, zPosition in the necessary range
107
//With "chooseFace" we will decide which face of the cube the Asteroid will spawn on
108
var chooseFace = rand.NextFloat(0,6);
109
110
//Based on what face was chosen, we x, y or z to a perimeter value
111
//(not important to learn ECS, just a way to make an interesting prespawned shape)
112
if (chooseFace < 1) {xPosition = -1*((settings.levelWidth)/2-padding);}
113
else if (chooseFace < 2) {xPosition = (settings.levelWidth)/2-padding;}
114
else if (chooseFace < 3) {yPosition = -1*((settings.levelHeight)/2-padding);}
115
else if (chooseFace < 4) {yPosition = (settings.levelHeight)/2-padding;}
116
else if (chooseFace < 5) {zPosition = -1*((settings.levelDepth)/2-padding);}
117
else if (chooseFace < 6) {zPosition = (settings.levelDepth)/2-padding;}
118
​
119
//we then create a new translation component with the randomly generated x, y, and z values
120
var pos = new Translation{Value = new float3(xPosition, yPosition, zPosition)};
121
​
122
//on our command buffer we record creating an entity from our Asteroid prefab
123
var e = commandBuffer.Instantiate(asteroidPrefab);
124
​
125
//we then set the Translation component of the Asteroid prefab equal to our new translation component
126
commandBuffer.SetComponent(e, pos);
127
​
128
//We will now set the PhysicsVelocity of our asteroids
129
//here we generate a random Vector3 with x, y and z between -1 and 1
130
var randomVel = new Vector3(rand.NextFloat(-1f, 1f), rand.NextFloat(-1f, 1f), rand.NextFloat(-1f, 1f));
131
//next we normalize it so it has a magnitude of 1
132
randomVel.Normalize();
133
//now we set the magnitude equal to the game settings
134
randomVel = randomVel * settings.asteroidVelocity;
135
//here we create a new VelocityComponent with the velocity data
136
var vel = new PhysicsVelocity{Linear = new float3(randomVel.x, randomVel.y, randomVel.z)};
137
//now we set the velocity component in our asteroid prefab
138
commandBuffer.SetComponent(e, vel);
139
​
140
}
141
}).Schedule();
142
​
143
//This will add our dependency to be played back on the BeginSimulationEntityCommandBuffer
144
m_BeginSimECB.AddJobHandleForProducer(Dependency);
145
}
146
}
Copied!
    This system is now set to run on the server only
    We have included a check for connected clients and a delete-all of asteroids if there are none collected to save CPU
    We grab our prefab from GhostCollection instead of PrefabCollection
    Let's move the AsteroidSpawnSystem file into Server/Systems folder
    Now, let's hit play and see what happens
Updating AsteroidSpawnSystem and hitting play
    Holy moly that's a lot of errors, let's focus on this one:
Error "Found a ghost in the ghost map which does not have an entity connected to it"
    One of the errors is that the client is running the two systems (1) AsteroidsOutOfBoundsSystem and (2) AsteroidsDestructionSystem and deleting the server-spawned interpolated ghosts (not good!)
      Only the server can decide what is destroyed and the ultimate "state" of the game
        This is the "authoritative" part of NetCode's authoritative server client-predicted model
      We need to update those two systems to only run on the server
    You will also notice there is now a bigger delay before the asteroids "appear"
      That is because now the asteroid snapshots must be sent to the client before they are spawned
      The wait for the data transfer creates the delay
    Let's start with updating AsteroidsOutOfBoundsSystem by updating the code in AsteroidsOutOfBoundsSystem.cs to:
1
using Unity.Burst;
2
using Unity.Entities;
3
using Unity.Collections;
4
using Unity.Mathematics;
5
using Unity.Jobs;
6
using Unity.Transforms;
7
using UnityEngine;
8
using Unity.NetCode;
9
​
10
​
11
//We cannot use [UpdateInGroup(typeof(ServerSimulationSystemGroup))] because we already have a group defined
12
//So we specify instead what world the system must run, ServerWorld
13
[UpdateInWorld(UpdateInWorld.TargetWorld.Server)]
14
//We are adding this system within the FixedStepSimulationGroup
15
[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
16
[UpdateBefore(typeof(EndFixedStepSimulationEntityCommandBufferSystem))]
17
public class AsteroidsOutOfBoundsSystem : SystemBase
18
{
19
//We are going to use the EndFixedStepSimECB
20
//This is because when we use Unity Physics our physics will run in the FixedStepSimulationSystem
21
//We are dipping our toes into placing our systems in specific system groups
22
//The FixedStepSimGroup has its own EntityCommandBufferSystem we will use to make the structural change
23
//of adding the DestroyTag
24
private EndFixedStepSimulationEntityCommandBufferSystem m_EndFixedStepSimECB;
25
26
protected override void OnCreate()
27
{
28
//We grab the EndFixedStepSimECB for our OnUpdate
29
m_EndFixedStepSimECB = World.GetOrCreateSystem<EndFixedStepSimulationEntityCommandBufferSystem>();
30
31
//We want to make sure we don't update until we have our GameSettingsComponent
32
//because we need the data from this component to know where the perimeter of our cube is
33
RequireSingletonForUpdate<GameSettingsComponent>();
34
}
35
​
36
protected override void OnUpdate()
37
{
38
//We want to run this as parallel jobs so we need to add "AsParallelWriter" when creating
39
//our command buffer
40
var commandBuffer = m_EndFixedStepSimECB.CreateCommandBuffer().AsParallelWriter();
41
​
42
//We must declare our local variables that we will use in our job
43
var settings = GetSingleton<GameSettingsComponent>();
44
​
45
//This time we query entities with components by using "WithAll" tag
46
//This makes sure that we only grab entities with an AsteroidTag component so we don't affect other entities
47
//that might have passed the perimeter of the cube
48
Entities
49
.WithAll<AsteroidTag>()
50
.ForEach((Entity entity, int nativeThreadIndex, in Translation position) =>
51
{
52
//We check if the current Translation value is out of bounds
53
if (Mathf.Abs(position.Value.x) > settings.levelWidth/2 ||
54
Mathf.Abs(position.Value.y) > settings.levelHeight/2 ||
55
Mathf.Abs(position.Value.z) > settings.levelDepth/2)
56
{
57
//If it is out of bounds wee add the DestroyTag component to the entity and return
58
commandBuffer.AddComponent(nativeThreadIndex, entity, new DestroyTag());
59
return;
60
}
61
​
62
}).ScheduleParallel();
63
​
64
//We add the dependencies to the CommandBuffer that will be playing back these structural changes (adding a DestroyTag)
65
m_EndFixedStepSimECB.AddJobHandleForProducer(Dependency);
66
67
}
68
}
Copied!
    Next, update AsteroidsDestructionSystem by updating the code in AsteroidsDestructionSystem.cs to:
1
using Unity.Burst;
2
using Unity.Entities;
3
using Unity.Collections;
4
using Unity.Mathematics;
5
using Unity.Jobs;
6
using Unity.Transforms;
7
using UnityEngine;
8
using Unity.NetCode;
9
​
10
//We cannot use [UpdateInGroup(typeof(ServerSimulationSystemGroup))] because we already have a group defined
11
//So we specify instead what world the system must run, ServerWorld
12
[UpdateInWorld(UpdateInWorld.TargetWorld.Server)]
13
//We are going to update LATE once all other systems are complete
14
//because we don't want to destroy the Entity before other systems have
15
//had a chance to interact with it if they need to
16
[UpdateInGroup(typeof(LateSimulationSystemGroup))]
17
public class AsteroidsDestructionSystem : SystemBase
18
{
19
private EndSimulationEntityCommandBufferSystem m_EndSimEcb;
20
​
21
protected override void OnCreate()
22
{
23
//We grab the EndSimulationEntityCommandBufferSystem to record our structural changes
24
m_EndSimEcb = World.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>();
25
}
26
27
protected override void OnUpdate()
28
{
29
//We add "AsParallelWriter" when we create our command buffer because we want
30
//to run our jobs in parallel
31
var commandBuffer = m_EndSimEcb.CreateCommandBuffer().AsParallelWriter();
32
​
33
//We now any entities with a DestroyTag and an AsteroidTag
34
//We could just query for a DestroyTag, but we might want to run different processes
35
//if different entities are destroyed, so we made this one specifically for Asteroids
36
Entities
37
.WithAll<DestroyTag, AsteroidTag>()
38
.ForEach((Entity entity, int nativeThreadIndex) =>
39
{
40
commandBuffer.DestroyEntity(nativeThreadIndex, entity);
41
​
42
}).ScheduleParallel();
43
​
44
//We then add the dependencies of these jobs to the EndSimulationEntityCOmmandBufferSystem
45
//that will be playing back the structural changes recorded in this sytem
46
m_EndSimEcb.AddJobHandleForProducer(Dependency);
47
48
}
49
}
Copied!
    Move both system files into the Server/Systems folder and hit play
Updating the asteroid systems, moving them into Server/Systems folder, and hitting play
    Looking much better!
    Let's do some housekeeping:
      Move AsteroidAuthoringComponent into Server/Components
      Move AsteroidTag into Mixed/Components
      Move DestroyTag into Mixed/Components
    No gif here, we believe in you πŸ’ͺ
We now have server-spawned asteroids appearing on the client
    We added a GhostAuthoring component on our Asteroid prefab
    We updated our AsteroidSpawnSystem, AsteroidsOutOfBoundsSystem, and AsteroidsDestructionSystem
Github branch link:
git clone https://github.com/moetsi/Unity-DOTS-Multiplayer-XR-Sample/ git checkout 'Updating-Asteroids'
Last modified 7mo ago