Helpful Code Blocks and Templates – Unity ECS

Here is a collection of snippets I have found to be used most frequently in Unity ECS development.

I always make note and copy the ones that I use most often for quick reference later. I hope it can be helpful to someone else working with ECS.

I will keep adding to this list as I continue to work with ECS, so check back from time to time!

Spawn an Entity from a Prefab

Copy to Clipboard

Creating an Entity From Prefab With IDeclareReferencedPrefabs

Copy to Clipboard

Component System Groups

Copy to Clipboard

Simple Query Definition

Copy to Clipboard

Query With Filtering

Copy to Clipboard

Jobs and Systems

MoverSystem

Copy to Clipboard

Simple Job

Copy to Clipboard

.ForEach with Burst and EntityCommandBuffer

Copy to Clipboard

IJobChunk with EntityCommandBuffer

Copy to Clipboard

Unity.Physics and Havok

Raycast – RaycastHit

Copy to Clipboard

Unity.Physics Collision Event Handler

Copy to Clipboard

ShaderGraph with Unity ECS

Custom ShaderGraph material property overrides


You can create your own custom ShaderGraph properties, and expose them to Unity DOTS as IComponentData. This allows you to write C#/Burst code to setup and animate your own shader inputs.

Enable Hybrid Instanced (experimental) checkbox in your ShaderGraph custom property:

Then write a DOTS IComponentData struct:

Copy to Clipboard

Ensure that the Reference name in ShaderGraph and the string name in MaterialProperty attribute match exactly. The type declared in the MaterialPropertyFormat should also be compatible with both the ShaderGraph and the struct data layout. If the binary size doesn’t match, you will see an error message in the console window.

Now you can write Burst C# system to animate your material property:

Copy to Clipboard

Important: You need to create a matching IComponentData struct (described above) for every custom ShaderGraph property that has Hybrid Instanced (experimental) enabled. If you fail to do so, Hybrid Renderer will not fill these properties: Hybrid Renderer V1 leaves the data uninitialized (flickering), and Hybrid Renderer V2 zero fills the data.

Special thanks to:

GameDevBrothers.com
Unity Documentation
Havok Physics Team on Unity Forums petarmHavok
Unity.Physics team
Unity ECS team