### Load content by URL and wait for completion Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/content-management-delivery.md This example demonstrates loading content by URL, waiting for the download, installation, and caching to complete, and then proceeding with application logic. It's suitable for use in a MonoBehaviour before the application starts, or in a system's update method if Burst compilation and job usage are not required. ```csharp using Unity.Entities; using Unity.Services.Core; using UnityEngine; public class DeliverContent : MonoBehaviour { async void Start() { await UnityServices.InitializeAsync(); var contentDeliveryService = ContentDeliveryService.Instance; await contentDeliveryService.SetupContentDeliveryServiceAsync(); var content = await contentDeliveryService.LoadContentByUrlAsync("https://example.com/content/mycontent.archive"); await contentDeliveryService.InstallContentAsync(content); // Content is now installed and cached. Load objects by weak reference ID. // var myObject = await contentDeliveryService.LoadObjectByIdAsync(content.id, "my_object_guid"); Debug.Log("Content loaded and installed."); } } ``` -------------------------------- ### Full example: Move entities towards target using IJobChunk Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/systems-looking-up-data.md This complete system example demonstrates how to move entities towards their target by using `IJobChunk` with `ComponentLookup` to access `Translation` and `Target` components. It calculates the direction and rotation needed to face the target. ```csharp using Unity.Entities; using Unity.Transforms; using Unity.Mathematics; using Unity.Collections; using Unity.Jobs; public partial class LookupDataExamples : SystemBase { protected override void OnUpdate() { // Declare and set the ComponentLookup for Translation components. // The 'true' argument indicates that we want read access. var translationsLookup = GetComponentLookup(true); // Declare and set the ComponentLookup for Target components. // The 'true' argument indicates that we want read access. var targetsLookup = GetComponentLookup(true); // Create an instance of the job. var lookupJob = new LookupIJobChunk { Translations = translationsLookup, Targets = targetsLookup }; // Schedule the job to run. // The job will process entities in parallel. lookupJob.Schedule(); } } [BurstCompile] public partial struct LookupIJobChunk : IJobEntity { // ComponentLookup for Translation components, used to read positions. [ReadOnly] public ComponentLookup Translations; // ComponentLookup for Target components, used to get the target entity. [ReadOnly] public ComponentLookup Targets; // Execute method is called for each entity that matches the query. // 'entity' is the current entity being processed. // '[Fragment] Target target' is a fragment component that provides the Target data. public void Execute(Entity entity, [Fragment] Target target) { // Get the target entity from the Target component. var targetEntity = target.TargetEntity; // Check if the target entity is valid and different from the current entity. if (targetEntity != Entity.Null && targetEntity != entity) { // Look up the Translation component of the target entity. var targetPosition = Translations[targetEntity]; // Look up the Translation component of the current entity. var trackingPosition = Translations[entity]; // Calculate the direction vector from the tracking entity to the target entity. var direction = targetPosition.Value - trackingPosition.Value; // Calculate the rotation needed to face the target. var rotation = quaternion.LookRotation(direction, Vector3.up); // Set the Rotation component of the current entity to face the target. // Note: This requires write access to the Rotation component. // If Rotation is not declared as writable in the job, this line will cause an error. // For simplicity, we assume Rotation is writable here. // SetComponent(entity, new Rotation { Value = rotation }); // This line is commented out as it requires write access } } } ``` -------------------------------- ### Entities.ForEach Example with Velocity and ObjectPosition Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/iterating-entities-foreach-define.md This example demonstrates a SystemBase implementation using Entities.ForEach to read the Velocity component and write to the ObjectPosition component. It shows how to schedule the job using ScheduleParallel. ```csharp public partial class LambdaJobExample : SystemBase { protected override void OnUpdate() { // Schedule the job to run in parallel Entities.ForEach((ref Velocity velocity, ref ObjectPosition objectPosition) => { // Read Velocity and write to ObjectPosition objectPosition.Value = velocity.Value; }).ScheduleParallel(); } } ``` -------------------------------- ### Complete HelloWorld.cs script Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/ecs-workflow-example-starter.md The complete C# script for the starter ECS workflow example, including the component and system definitions. ```csharp using Unity.Entities; using Unity.Core; using Unity.Collections; // Define the component based on IComponentData public struct HelloComponent : IComponentData { public FixedString32Bytes Message; } // Define the system based on SystemBase public partial class ExampleSystem : SystemBase { protected override void OnCreate() { // Create a new entity from the world var entity = EntityManager.CreateEntity(); // Add a HelloComponent component to the entity var helloComponent = new HelloComponent { Message = "Hello ECS World" }; EntityManager.AddComponentData(entity, helloComponent); // Set the name of the entity for debugging purposes EntityManager.SetName(entity, "Hello World Entity"); } protected override void OnUpdate() { // Query for all entities that have the HelloComponent component Entities.ForEach((HelloComponent component) => { // Log the message from the component to the console UnityEngine.Debug.Log(component.Message.ToString()); }).WithoutBurst().Run(); } } ``` -------------------------------- ### Setup BufferLookup in a system Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/components-buffer-jobs.md In your system, declare a BufferLookup, initialize it using SystemState.GetBufferLookup in OnCreate, and update it in OnUpdate before passing it to your job. ```csharp public partial class AccessBufferSystem : SystemBase { private BufferLookup _buffers; protected override void OnCreate() { // Get the BufferLookup for the dynamic buffer type _buffers = SystemState.GetBufferLookup(true); } protected override void OnUpdate() { // Update the lookup table with the latest buffer data _buffers.Update(this); // Create and schedule the job, passing the lookup table var job = new AccessBufferJob { Buffers = _buffers }; // Schedule the job // ... jobHandle = job.ScheduleParallel(); // ... Dependency = jobHandle; } } ``` -------------------------------- ### Simple Blob Asset Baker Example Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/blob-assets-create.md A straightforward example of a baker that creates and registers a blob asset. Ensure blob assets are registered with the baker to prevent unexpected de-allocation due to incorrect ref counting. ```csharp public void OnCreate(ref SystemState state) { // Create a BlobBuilder var blobBuilder = new BlobBuilder(); // Create the data for the blob asset ref MyBlobDataType data = ref blobBuilder.ConstructRoot(); data.Value = 10; // Build the blob asset var blobAsset = blobBuilder.Build(); // Register the blob asset with the baker // The baker will de-duplicate and ref-count the blob asset. AddBlobAsset(ref blobAsset); } ``` -------------------------------- ### Example Console Output for .hexpat File Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/entities-binary-debugging.md This message indicates that a pattern file has been created for the recent bake, along with its location and size. ```text Created an .hexpat file from the recent bake, located at: ./Library/GeneratedImHex/45a2c8428b97e4e48955d9b5114509fe.0.entities.hexpat (Size: 24154 bytes) ``` -------------------------------- ### Cleanup Component Lifecycle Example Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/components-cleanup-introducing.md Demonstrates the lifecycle of an entity with a cleanup component, including creation, partial destruction, and final removal. ```csharp // Creates an entity that contains a cleanup component. Entity e = EntityManager.CreateEntity( typeof(Translation), typeof(Rotation), typeof(ExampleCleanup)); // Attempts to destroy the entity but, because the entity has a cleanup component, Unity doesn't actually destroy the entity. Instead, Unity just removes the Translation and Rotation components. EntityManager.DestroyEntity(e); // The entity still exists so this demonstrates that you can still use the entity normally. EntityManager.AddComponent(e); // Removes all the remaining components from the entity. // Removing the final cleanup component (ExampleCleanup) automatically destroys the entity. EntityManager.RemoveComponent(e, new ComponentTypeSet(typeof(ExampleCleanup), typeof(Translation))); // Demonstrates that the entity no longer exists. entityExists is false. bool entityExists = EntityManager.Exists(e); ``` -------------------------------- ### Create and record commands with EntityCommandBufferSystem Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/systems-entity-command-buffer-automatic-playback.md Get a singleton EntityCommandBufferSystem to create an EntityCommandBuffer and record commands. Do not manually play back or dispose of ECBs created this way, as the system handles it automatically. ```csharp public class MySystem : SystemBase { protected override void OnUpdate() { // Get the ECB system var ecbSystem = World.GetOrCreateSystem(); // Create an ECB and record commands var ecb = ecbSystem.CreateCommandBuffer(); // ... record commands using ecb ... } } ``` -------------------------------- ### Blob Asset Baker Setup Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/blob-assets-create.md This code sets up the necessary components for registering a blob asset with a baker. It demonstrates how to create a BlobAssetReference using BlobBuilder and register it with the baker using `AddBlobAsset`. ```csharp public void OnCreate(ref SystemState state) { // ... other setup var blobAsset = BlobAssetBuilder.Build(blobBuilder); // Register the blob asset with the baker // The baker will de-duplicate and ref-count the blob asset. AddBlobAsset(ref blobAsset); // ... other setup } ``` -------------------------------- ### Entities.ForEach Lambda with Many Parameters and Entity Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/iterating-entities-foreach-define.md Use custom delegates for more than eight parameters or custom ordering. This example includes the 'entity' parameter. ```csharp [Unity.Entities.RegisterUpdateType(typeof(Source))] public partial class LambdaJobExamples : SystemBase { protected override void OnUpdate() { // Example of a lambda expression with 12 parameters: // - A read-only Source component. // - A writable Destination component. // - A read-only Another component. // - A writable Third component. // - A read-only Fourth component. // - A writable Fifth component. // - A read-only Sixth component. // - A writable Seventh component. // - A read-only Eighth component. // - A writable Ninth component. // - The entity itself. // - The entity's index in the query. Entities.ForEach((in Source source, ref Destination destination, in Another another, ref Third third, in Fourth fourth, ref Fifth fifth, in Sixth sixth, ref Seventh seventh, in Eighth eighth, ref Ninth ninth, Entity entity, int entityInQueryIndex) => { destination.value = source.value; third.value = another.value; fifth.value = fourth.value; seventh.value = sixth.value; ninth.value = eighth.value; }).Schedule(); } } public struct Source : IComponentData { public int value; } public struct Destination : IComponentData { public int value; } public struct Another : IComponentData { public int value; } public struct Third : IComponentData { public int value; } public struct Fourth : IComponentData { public int value; } public struct Fifth : IComponentData { public int value; } public struct Sixth : IComponentData { public int value; } public struct Seventh : IComponentData { public int value; } public struct Eighth : IComponentData { public int value; } public struct Ninth : IComponentData { public int value; } ``` -------------------------------- ### Create LocalTransform from Position Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/transforms-using.md Provides an example of creating a new LocalTransform with a specified position, while using default values for rotation and scale. ```csharp var myTransform = LocalTransform.FromPosition(1, 2, 3); ``` -------------------------------- ### Create a Tag Component Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/components-tag.md Define a tag component by creating an unmanaged component without any properties. This example demonstrates the basic structure for a tag component. ```csharp public struct MyTag : IComponentData { } ``` -------------------------------- ### Load Every Other Scene Section Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/streaming-scene-sections.md This example demonstrates how to load every other section of a given scene by adding the RequestSceneLoaded component to the section meta entity. Ensure section 0 loads first. ```csharp foreach (var sectionEntity in EntityManager.GetBuffer(sceneMetaEntity).Reversed()) { if (sectionEntity.SectionIndex % 2 == 0) { EntityManager.AddComponent(sectionEntity.SectionMetaEntity); } } ``` -------------------------------- ### Create a Blob Asset with an Internal Pointer Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/blob-assets-create.md Manually set internal pointers using the BlobPtr type. This example illustrates how to use BlobPtr for internal references. ```csharp BlobBuilder blobBuilder = new BlobBuilder(Allocator.Temp); ref MyPointerStruct root = ref blobBuilder.ConstructRoot(); BlobBuilder blobBuilder2 = new BlobBuilder(Allocator.Temp); ref MyStruct data = ref blobBuilder2.ConstructRoot(); data.Value = 1; root.Pointer = blobBuilder2.CreateBlobAssetReference(Allocator.Temp); blobBuilder.CreateBlobAssetReference(Allocator.Temp); blobBuilder.Dispose(); blobBuilder2.Dispose(); ``` -------------------------------- ### Destroy entities with ECB in Entities.ForEach Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/iterating-entities-foreach-ecb.md This example demonstrates how to check an entity's health and record a command to destroy it if the health is 0, using an EntityCommandBuffer within an Entities.ForEach loop. The EndSimulationEntityCommandBufferSystem is specified for command playback. ```csharp public partial class EcbParallelForSystem : SystemBase { protected override void OnUpdate() { var ecb = new EntityCommandBuffer(Allocator.Temp); // Entities.ForEach can take an EntityCommandBuffer parameter. // The compiler generates the code to create, populate, play back, and dispose of the ECB. // Only a small subset of EntityCommandBuffer methods are supported, and they have the [SupportedInEntitiesForEach] attribute. // For example, DestroyEntity, Instantiate, AddComponent, SetComponent, RemoveComponent. // When you use any of these methods in a ForEach method, at runtime the compiler generates the code necessary to create, populate, play back, and dispose of an EntityCommandBuffer instance, or an EntityCommandBuffer.ParallelWriter instance, if ScheduleParallel is called. // Invoking these methods outside of ForEach() results in an exception. Entities.ForEach((Entity entity, ref HealthLevel healthLevel) => { if (healthLevel.Value == 0) { // Record a command to destroy the entity. ecb.DestroyEntity(entity); } }).ScheduleParallel(); // Specify that the EndSimulationEntityCommandBufferSystem must play back the command. // This is required when using EntityCommandBuffer directly. // When using EntityCommandBuffer.ParallelWriter, this is handled automatically by the system. RequireForUpdate(); // Schedule the ECB playback. // This is required when using EntityCommandBuffer directly. // When using EntityCommandBuffer.ParallelWriter, this is handled automatically by the system. var ecbSystem = World.GetOrCreateSystem(); ecbSystem.AddJobHandleForProducer(Dependency); } } public struct HealthLevel : IComponentData { public int Value; } ``` -------------------------------- ### ISystem Template with BurstCompile Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Unity.Entities.Editor/ScriptTemplates/ISystemTemplate.txt This is a basic template for a Unity Entities system. Use this as a starting point for creating new systems. The BurstCompile attribute is used to enable high-performance code execution. ```csharp using Unity.Burst; using Unity.Entities; #ROOTNAMESPACEBEGIN# partial struct #SCRIPTNAME# : ISystem { [BurstCompile] public void OnCreate(ref SystemState state) { #NOTRIM# } [BurstCompile] public void OnUpdate(ref SystemState state) { #NOTRIM# } [BurstCompile] public void OnDestroy(ref SystemState state) { #NOTRIM# } } #ROOTNAMESPACEEND# ``` -------------------------------- ### Get Component Lookup Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/systems-systemapi.md Use this to get a read-only component lookup for passing into jobs. This method caches the lookup and updates it before job execution. ```csharp new MyJob{healthLookup=SystemAPI.GetComponentLookup(isReadOnly:true)}; ``` -------------------------------- ### Create a Baking System with Tag Component Logic Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/baking-baking-systems-overview.md This example demonstrates how to create a baking system by marking it with the `[WorldSystemFilter(WorldSystemFilterFlags.BakingSystem)]` attribute. It adds a tag component to entities that have a specific other component and includes logic to remove the tag if the component is no longer present, preventing orphaned tags. ```csharp [WorldSystemFilter(WorldSystemFilterFlags.BakingSystem)] public partial class BakingSystemExample : SystemBase { protected override void OnUpdate() { // Add a tag component to entities that have a specific component. // Remove the tag if the component is not present. Entities .WithAll() .ForEach((Entity entity, ref SomeTagComponent tag) => { // Component is present, tag is already there. }) .Without() .ForEach((Entity entity, ref SomeTagComponent tag) => { // Component is not present, remove the tag. EntityManager.RemoveComponent(entity); }); Entities .WithAll() .Without() .ForEach((Entity entity) => { // Component is present, but tag is not. Add the tag. EntityManager.AddComponent(entity); }); } } // Example components (replace with your actual components) public struct SomeComponent : IComponentData {} public struct SomeTagComponent : IComponentData {} ``` -------------------------------- ### Get Up Vector Using LocalToWorld and Math.normalize Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/transforms-comparison.md Use `math.normalize(SystemAPI.GetComponent(e).Up)` to get the normalized 'up' vector of an entity in world space. `normalize` can be omitted if the transform hierarchy is known to not have scaling. ```csharp float3 up(ref SystemState state, Entity e) { return math.normalize(SystemAPI.GetComponent(e).Up); } ``` -------------------------------- ### Add, Set, and Get Chunk Components Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/components-chunk-use.md Use EntityManager.AddChunkComponentData to add a chunk component. Query for chunks with specific components using ComponentType.ChunkComponent. Set and get chunk component data using EntityManager.SetChunkComponentData and EntityManager.GetChunkComponentData. ```csharp private void ChunkComponentExample(Entity e) { // Adds ExampleChunkComponent to the passed in entity's chunk. EntityManager.AddChunkComponentData(e); // Finds all chunks with an ExampleComponent and an ExampleChunkComponent. // To distinguish chunk components from a regular IComponentData, You must // specify the chunk component with ComponentType.ChunkComponent. EntityQuery query = GetEntityQuery(typeof(ExampleComponent), ComponentType.ChunkComponent()); NativeArray chunks = query.ToArchetypeChunkArray(Allocator.Temp); // Sets the ExampleChunkComponent value of the first chunk. EntityManager.SetChunkComponentData(chunks[0], new ExampleChunkComponent { Value = 6 }); // Gets the ExampleChunkComponent value of the first chunk. ExampleChunkComponent exampleChunkComponent = EntityManager.GetChunkComponentData(chunks[0]); Debug.Log(exampleChunkComponent.Value) // 6 } ``` -------------------------------- ### Component Lookup Initialization and Update Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/systems-systemapi.md Demonstrates the equivalent of SystemAPI.GetComponentLookup, showing manual initialization in OnCreate and update in OnUpdate for a component lookup. ```csharp ComponentLookup lookup_HealthData_RO; public void OnCreate(ref SystemState state){ lookup_HealthData_RO = state.GetComponentLookup(isReadOnly:true); } public void OnUpdate(ref SystemState state){ lookup_HealthData_RO.Update(ref state); new MyJob{healthLookup=lookup_HealthData_RO}; } ``` -------------------------------- ### Ship and Window Example with Transform Usage Flags Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/transforms-usage-flags.md Demonstrates how to apply different TransformUsageFlags to parent and child entities to optimize runtime behavior. The ship is marked as Dynamic to follow movement, while the window retains Renderable status. ```csharp public class TransformUsageFlagsExamples : MonoBehaviour { // A component that uses TransformUsageFlags. The ship is marked as Dynamic so it can move at runtime. // The window is marked as Renderable, so it has the necessary components to be rendered. // Unity automatically adds the correct transform components to ensure the window follows the ship. [SerializeField] private bool m_UseShipExample = false; [SerializeField] private GameObject m_ShipPrefab; [SerializeField] private GameObject m_WindowPrefab; public void Bake(Baker baker) { if (!m_UseShipExample) return; // The ship is marked as Dynamic so it can move at runtime. var shipEntity = baker.CreatePureEntity(); baker.AddComponent(shipEntity, new TransformUsageFlags(TransformUsageFlags.Dynamic)); baker.CreateGameObjectEntity(m_ShipPrefab, new GameObjectConversionSystem.Settings { Entity = shipEntity }); // The window is marked as Renderable, so it has the necessary components to be rendered. // Unity automatically adds the correct transform components to ensure the window follows the ship. var windowEntity = baker.CreatePureEntity(); baker.AddComponent(windowEntity, new TransformUsageFlags(TransformUsageFlags.Renderable)); baker.CreateGameObjectEntity(m_WindowPrefab, new GameObjectConversionSystem.Settings { Entity = windowEntity }); } } ``` -------------------------------- ### DisableAutoCreationAttribute Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/api_index.md Prevents a system from being automatically discovered and run when your application starts up. ```APIDOC ## Attribute DisableAutoCreationAttribute ### Description Prevents a system from being automatically discovered and run when your application starts up. ### Usage ```csharp [DisableAutoCreation] public partial class MySystem : SystemBase { // ... } ``` ``` -------------------------------- ### Get World Position in ECS Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/transforms-comparison.md Retrieve the world position of an entity using LocalToWorld.Position. ```csharp float3 position(ref SystemState state, Entity e) { return SystemAPI.GetComponent(e).Position; } ``` -------------------------------- ### Get Local Rotation in ECS Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/transforms-comparison.md Retrieve the local rotation of an entity using LocalTransform.Rotation. ```csharp quaternion localRotation(ref SystemState state, Entity e) { return SystemAPI.GetComponent(e).Rotation; } ``` -------------------------------- ### Control System Creation Order with CreateAfter Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/systems-update-order.md Ensure a system's OnCreate method runs after another system's OnCreate by using the CreateAfter attribute. Use World.GetExistingSystem to retrieve the dependency. ```csharp [CreateAfter(typeof(OtherSystem))] public partial class MySystem : SystemBase { protected override void OnCreate() { // Ensure OtherSystem.OnCreate has finished before this runs var otherSystem = World.GetExistingSystem(); } } ``` -------------------------------- ### Get Local Position in ECS Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/transforms-comparison.md Retrieve the local position of an entity using LocalTransform.Position. ```csharp float3 localPosition(ref SystemState state, Entity e) { return SystemAPI.GetComponent(e).Position; } ``` -------------------------------- ### Get Parent Entity in ECS Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/transforms-comparison.md Retrieve the parent entity of the current entity using Parent.Value. ```csharp Entity parent(ref SystemState state, Entity e) { return SystemAPI.GetComponent(e).Value; } ``` -------------------------------- ### Get Local to World Matrix in ECS Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/transforms-comparison.md Retrieve the local-to-world transformation matrix for an entity using LocalToWorld.Value. ```csharp float4x4 localToWorldMatrix(ref SystemState state, Entity e) { return SystemAPI.GetComponent(e).Value; } ``` -------------------------------- ### Define Custom World Initialization with ICustomBootstrap Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/systems-icustombootstrap.md Implement this interface to control world creation before the default Unity initialization. Returning true prevents the default bootstrap from running. ```csharp public interface ICustomBootstrap { // Create your own set of worlds or your own custom default world in this method. // If true is returned, the default world bootstrap doesn't run at all and no additional worlds are created. bool Initialize(string defaultWorldName); } ``` -------------------------------- ### Get Child Count in ECS Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/transforms-comparison.md Use SystemAPI.GetBuffer with the Child component to retrieve the number of children an entity has. ```csharp int childCount(ref SystemState state, Entity e) { return SystemAPI.GetBuffer(e).Length; } ``` -------------------------------- ### Build EntityQuery with SystemAPI.QueryBuilder Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/systems-systemapi.md Use SystemAPI.QueryBuilder to get a cached EntityQuery. This method is compiled by ECS into a direct instantiation. ```csharp /// SystemAPI call SystemAPI.QueryBuilder().WithAll().Build(); /// ECS compiles it like so: EntityQuery query; public void OnCreate(ref SystemState state){ query = new EntityQueryBuilder(state.WorldUpdateAllocator).WithAll().Build(ref state); } public void OnUpdate(ref SystemState state){ query; } ``` -------------------------------- ### ICustomBootstrap Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/api_index.md An interface to implement to create your own system loop. ```APIDOC ## Interface ICustomBootstrap ### Description An interface to implement to create your own system loop. ### Usage ```csharp // Example implementation of ICustomBootstrap ``` ``` -------------------------------- ### Dependency Completion for Singletons Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/components-singleton.md Information on handling dependencies when using singleton component APIs, especially with read/write access. ```APIDOC ## Dependency Completion ### Description Singleton API calls do not automatically ensure that running jobs are completed first. Manual completion or restructuring of data dependencies is required. ### Methods for Manual Completion - **EntityManager.CompleteDependencyBeforeRO**: Completes dependencies before read-only access. - **EntityManager.CompleteDependencyBeforeRW**: Completes dependencies before read/write access. ### Best Practices for GetSingletonRW - Use only to access a `NativeContainer` in a component. - Check the Jobs Debugger for errors and restructure or manually complete dependencies as needed. ``` -------------------------------- ### Create an ECS system with OnCreate and OnUpdate Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/ecs-workflow-example-starter.md Implements an ECS system that creates an entity with HelloComponent in OnCreate and logs a message from the component in OnUpdate. ```csharp public partial class ExampleSystem : SystemBase { protected override void OnCreate() { // Create a new entity from the world var entity = EntityManager.CreateEntity(); // Add a HelloComponent component to the entity var helloComponent = new HelloComponent { Message = "Hello ECS World" }; EntityManager.AddComponentData(entity, helloComponent); // Set the name of the entity for debugging purposes EntityManager.SetName(entity, "Hello World Entity"); } protected override void OnUpdate() { // Query for all entities that have the HelloComponent component Entities.ForEach((HelloComponent component) => { // Log the message from the component to the console UnityEngine.Debug.Log(component.Message.ToString()); }).WithoutBurst().Run(); } } ``` -------------------------------- ### Get Rotation Using LocalToWorld Component Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/transforms-comparison.md Use `LocalToWorld.Value.Rotation()` to retrieve the rotation of an entity in world space. This is the DOTS equivalent of `UnityEngine.Transform.rotation`. ```csharp quaternion rotation(ref SystemState state, Entity e) { return SystemAPI.GetComponent(e).Value.Rotation(); } ``` -------------------------------- ### Create archetype and entity in a Burst-friendly way Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/optimize-structural-changes.md This C# code demonstrates how to create an entity with an initial set of components in a Burst-friendly manner. It's useful for setting up entities before adding more components later. ```csharp // create archetype and entity in a Burst-friendly way var abComponents = new FixedList128Bytes { ComponentType.ReadWrite(), ComponentType.ReadWrite(), }.ToNativeArray(state.WorldUpdateAllocator); var abArchetype = state.EntityManager.CreateArchetype(abComponents); var entity = state.EntityManager.CreateEntity(abArchetype); // ... Some time later... state.EntityManager.AddComponent(entity); ``` -------------------------------- ### Instantiate a prefab using SystemAPI Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/reference-unity-objects.md Access and instantiate a prefab referenced by UnityObjectRef using SystemAPI within a system. This allows for dynamic instantiation of prefabs in your ECS world. ```csharp public partial class SpawnSystem : SystemBase { protected override void OnUpdate() { Entities.ForEach((Entity entity, ref MyComponent myComponent) => { if (myComponent.Prefab.HasValue) { var spawnedEntity = Instantiate(myComponent.Prefab.Value, Vector3.zero, Quaternion.identity); // You can now work with the spawned entity and its components } }).Run(); } } ``` -------------------------------- ### SpawnerSystem C# Script Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/ecs-workflow-example-prefab-instantiation.md This is the main C# script for the SpawnerSystem, which handles the instantiation of entity prefabs. It includes logic for ensuring the system runs at the correct time and for instantiating and positioning new entities. ```csharp using Unity.Entities; using Unity.Transforms; using Unity.Mathematics; public partial class SpawnerSystem : SystemBase { protected override void OnUpdate() { // Ensure the system runs only when a Spawner component is available. state.RequireForUpdate(); // Get the singleton Spawner component. Spawner spawner = SystemAPI.GetSingleton(); // Generate a random number for position offset. var random = new Random(spawner.Seed + (uint)Time.ElapsedTime); // Instantiate prefabs. for (int i = 0; i < spawner.Count; i++) { // Instantiate the prefab. Entity newEntity = state.EntityManager.Instantiate(spawner.Prefab); // Calculate a random position within a small vicinity. float3 newPosition = CalculateNewPosition(spawner.Position, random); // Set the local transform component for the new entity. state.EntityManager.SetComponentData(newEntity, LocalTransform.FromPosition(newPosition)); } } // Helper method to calculate a new random position. private float3 CalculateNewPosition(float3 spawnerPosition, Random random) { float3 offset = random.NextFloat3Direction() * spawner.Range; return spawnerPosition + offset; } } ``` -------------------------------- ### Authoring Component Structure Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Unity.Entities.Editor/ScriptTemplates/BakerTemplate.txt Defines the basic structure of an authoring component MonoBehaviour. Use this as a starting point for your custom authoring components. ```csharp using Unity.Entities; using UnityEngine; #ROOTNAMESPACEBEGIN# class #SCRIPTNAME# : MonoBehaviour { #NOTRIM# } class #SCRIPTNAME#Baker : Baker<#SCRIPTNAME#> { public override void Bake(#SCRIPTNAME# authoring) { #NOTRIM# } } #ROOTNAMESPACEEND# ``` -------------------------------- ### Alternative iteration for LocalTransform and RotationSpeed components Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/systems-systemapi-query.md This alternative demonstrates iterating through entities with LocalTransform and RotationSpeed components without explicitly specifying RefRO for RotationSpeed. It achieves the same result as the previous example but with slightly less verbose syntax for read-only components. ```csharp foreach (var group in SystemAPI.Query, RotationSpeed>().WithAll()) { var transform = group.Item1; var rotationSpeed = group.Item2; transform.ValueRW.Position += transform.ValueRW.Forward() * rotationSpeed.Speed * System.Time.DeltaTime; } ``` -------------------------------- ### Manage System Group Allocator with World Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/allocators-system-group.md Demonstrates using `World.SetGroupAllocator` and `World.RestoreGroupAllocator` within `IRateManager.ShouldGroupUpdate` to swap the world update allocator with the system group allocator and restore it. ```csharp public class SystemGroupAllocatorExample : ComponentSystemGroup { protected override void OnUpdate() { // Example of using World.SetGroupAllocator and World.RestoreGroupAllocator // within IRateManager.ShouldGroupUpdate (not shown here). // This is typically handled internally by the system group. base.OnUpdate(); } } ``` -------------------------------- ### Define Health and Color Components Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/systems-write-groups.md These components represent the health state and color of an entity. They are part of the example demonstrating write group functionality. ```csharp public struct HealthComponent : IComponentData { public int Value; } ``` ```csharp public struct ColorComponent : IComponentData { public float4 Value; } ``` -------------------------------- ### Filter Archetypes with Specific Components Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/systems-entityquery-create.md This example demonstrates how to exclude archetypes containing a specific component (Static) while including others that have ObjectRotation and ObjectRotationSpeed. ```csharp public EntityQuery _objectRotationQuery = EntityManager.CreateEntityQuery(new EntityQueryDesc { All = new ComponentType[] { typeof(ObjectRotation), typeof(ObjectRotationSpeed) }, None = new ComponentType[] { typeof(Static) } }); ``` -------------------------------- ### Multi-threaded Spawner system with IJobEntity Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/ecs-workflow-example-prefab-instantiation.md This C# code demonstrates how to update a Spawner system to utilize multi-threading with IJobEntity. It requires an entity command buffer to record entity creation commands, which are then played back on the main thread. Ensure you have enough GameObjects to distribute the workload across multiple threads. ```csharp using Unity.Burst; using Unity.Entities; using Unity.Jobs; using Unity.Transforms; public partial struct SpawnerSystemMultithreaded : ISystem { [BurstCompile] public void OnCreate(ref SystemState state) { state.RequireForUpdate(); } [BurstCompile] public void OnUpdate(ref SystemState state) { var spawner = SystemAPI.GetSingleton(); var ecb = new EntityCommandBuffer(Unity.Collections.Allocator.Temp); state.Dependency = JobChunkExtensions.JobChunkDependency ( state.Dependency, SystemAPI.GetProducer ( new SpawnJob { Ecb = ecb, Spawner = spawner } ) ); } [BurstCompile] partial struct SpawnJob : IJobEntity { public EntityCommandBuffer Ecb; public Spawner Spawner; void Execute(SpawnerComponent spawnerComponent, LocalTransform transform, Unity.Entities.World world) { var entity = Ecb.Instantiate(Spawner.Prefab); Ecb.SetComponent(entity, new LocalTransform { Position = transform.Position + Unity.Mathematics.math.randomizes(new Unity.Mathematics.Random(100), 10f) * 10f, Rotation = transform.Rotation, Scale = transform.Scale }); } } } ``` -------------------------------- ### Apply Instance Transformation System Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/streaming-scene-instancing.md A system that applies transformations to entities within an instanced scene. It queries for `PostLoadOffset` data and applies it to the scene's entities. ```csharp [UpdateInGroup(typeof(ProcessAfterLoadGroup))] public partial class ApplyInstanceTransform : SystemBase { protected override void OnUpdate() { // Query for scene meta entities with PostLoadOffset and PostLoadCommandBuffer Entities .WithAll() .WithAll() .ForEach((Entity sceneMetaEntity, ref PostLoadOffset offset) => { // Get the EntityCommandBuffer from the PostLoadCommandBuffer var ecbArray = EntityManager.GetBuffer(sceneMetaEntity); if (ecbArray.Length == 0) return; var ecb = ecbArray[0]; // Apply the offset to all entities in the scene instance // Note: In a real scenario, you'd likely query entities within the scene instance // and apply transforms based on their original positions or other logic. // For simplicity, this example assumes all entities in the instance should be offset. var query = EntityManager.CreateEntityQuery(typeof(Translation)); var translations = query.ToComponentDataArray(Allocator.Temp); foreach (var translation in translations) { // This is a simplified example. In practice, you'd modify existing entities. // EntityManager.SetComponentData(entity, new Translation { Value = translation.Value + offset.Offset }); } translations.Dispose(); // Dispose the EntityCommandBuffer after use ecb.Dispose(); EntityManager.RemoveComponent(sceneMetaEntity); }).Run(); } } ``` -------------------------------- ### Load Scene as New Instance Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/streaming-scene-instancing.md Load a scene asynchronously as a new instance using `SceneLoadFlags.NewInstance`. Store the returned scene meta entity for further processing. ```csharp var scene = SceneSystem.LoadSceneAsync("Assets/Scenes/MyScene.unity", SceneLoadFlags.NewInstance); await scene.ToTask(); var sceneMetaEntity = scene.Scene.MetaEntity; var ecb = new EntityCommandBuffer(Allocator.Temp); // Add custom instance data ecb.AddComponent(sceneMetaEntity, new PostLoadOffset { Offset = new float3(10, 0, 0) }); // Add PostLoadCommandBuffer to the scene meta entity var postLoadCommandBuffer = default(PostLoadCommandBuffer); postLoadCommandBuffer.AddBuffer(sceneMetaEntity).Add(ecb); SceneSystem.AppendInitSystemToUpdate(sceneMetaEntity, typeof(ApplyInstanceTransform)); ``` -------------------------------- ### Get Right Vector in ECS Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/transforms-comparison.md Calculate the right vector of an entity using LocalToWorld.Right. Normalize the result if the transform hierarchy might contain scaling. ```csharp float3 right(ref SystemState state, Entity e) { return math.normalize(SystemAPI.GetComponent(e).Right); } ``` -------------------------------- ### Get Forward Vector in ECS Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/transforms-comparison.md Calculate the forward vector of an entity using LocalToWorld.Forward. Normalize the result if the transform hierarchy might contain scaling. ```csharp float3 forward(ref SystemState state, Entity e) { return math.normalize(SystemAPI.GetComponent(e).Forward); } ``` -------------------------------- ### Create an IJobEntity job Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/iterating-data-ijobentity.md Implement IJobEntity and its Execute method to create a job that iterates over component data. Use the 'partial' keyword as source generation creates the IJobChunk implementation. ```csharp public partial struct SimpleSample : IJobEntity { public void Execute(SampleComponent sampleComponent) { sampleComponent.Value += 1; } } ``` -------------------------------- ### IJobEntity Template Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Unity.Entities.Editor/ScriptTemplates/IJobEntityTemplate.txt Use this template to define a new IJobEntity system. Replace #SCRIPTNAME# with your desired system name and implement the Execute method. ```csharp using Unity.Entities; #ROOTNAMESPACEBEGIN# public partial struct #SCRIPTNAME# : IJobEntity { public void Execute() { #NOTRIM# } } #ROOTNAMESPACEEND# ``` -------------------------------- ### Dispose Blob Asset Reference at Runtime Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/blob-assets-create.md Blob assets allocated at runtime with CreateBlobAssetReference must be disposed manually. This example shows how to dispose of such a reference. ```csharp BlobAssetReference myBlobAsset = BlobAssetReference.Null; // ... create and use myBlobAsset ... if (myBlobAsset.IsCreated) { myBlobAsset.Dispose(); } ``` -------------------------------- ### Create a Blob Asset with an Array Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/blob-assets-create.md To include arrays within blob assets, use the BlobArray type. This example demonstrates allocating and filling a BlobArray. ```csharp BlobBuilder blobBuilder = new BlobBuilder(Allocator.Temp); ref MyArrayStruct root = ref blobBuilder.ConstructRoot(); BlobArrayBuilder blobArrayBuilder = blobBuilder.Allocate(ref root.Array, 5); for (int i = 0; i < blobArrayBuilder.Length; i++) { blobArrayBuilder[i] = i; } blobBuilder.CreateBlobAssetReference(Allocator.Temp); blobBuilder.Dispose(); ``` -------------------------------- ### Multi Playback with EntityCommandBuffer Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/systems-entity-command-buffer-playback.md Create an EntityCommandBuffer with `PlaybackPolicy.MultiPlayback` to allow calling the `Playback` method more than once. This is useful for repeatedly spawning sets of entities. ```csharp using Unity.Entities; // Create an ECB with MultiPlayback policy var ecb = new EntityCommandBuffer(Unity.Collections.Allocator.Temp, PlaybackPolicy.MultiPlayback); // Record commands // ecb.Instantiate(entityPrefab); // Play back commands the first time ecb.Playback(World.Active); // Play back commands a second time ecb.Playback(World.Active); // Dispose the ECB when done ecb.Dispose(); ``` -------------------------------- ### Define and Use CannonBallAspect Source: https://github.com/needle-mirror/com.unity.entities/blob/master/Documentation~/aspects-create.md An example of a CannonBallAspect that sets transform, position, and speed. It demonstrates how to define an aspect for game-specific components and use it within a job. ```csharp [code-cs[aspects](../DocCodeSamples.Tests/AspectExamples.cs#aspect-example)] ``` ```csharp using Unity.Entities; using Unity.Burst; // It's best practice to Burst-compile your code [BurstCompile] partial struct CannonBallJob : IJobEntity { void Execute(CannonBallAspect cannonBall) { // Your game logic } } ```