Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Getting a Reference to a Material in SystemBase

Discussion in 'Entity Component System' started by roryo, Sep 30, 2020.

  1. roryo

    roryo

    Joined:
    May 21, 2009
    Posts:
    1,479
    I am creating a system that initializes the scene with a set of boxes. For the RenderMesh component, I need a reference to a Material. How can one define the Material to be used in the System?

    Here's my code so far:

    Code (CSharp):
    1. using UnityEngine;
    2. using Unity.Collections;
    3. using Unity.Collections.LowLevel.Unsafe;
    4.  
    5. using Unity.Entities;
    6. using Unity.Transforms;
    7. using Unity.Rendering;
    8. using UnityEngine.Rendering;
    9. using Unity.Mathematics;
    10. using Unity.Physics;
    11. using Collider = Unity.Physics.Collider;
    12.  
    13. using Unity.Physics.Extensions;
    14.  
    15.  
    16. public class BootstrapSystem : SystemBase
    17. {
    18.  
    19.     EntityManager entityManager;
    20.  
    21.  
    22.     protected override void OnStartRunning()
    23.     {
    24.         entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
    25.  
    26.         for (int i = 0; i < 10; i++)
    27.         {
    28.             CreateBox(new Vector3(1, 1, 1), new float3(0f, i * 1f, 0), 2);
    29.         }
    30.     }
    31.    
    32.  
    33.     private Entity CreateBox(Vector3 size, float3 trans, float mass)
    34.     {
    35.         Mesh mesh = BoxMesh.CreateBoxMesh(size.x, size.y, size.z);
    36.  
    37.         RenderMesh rm = new RenderMesh()
    38.         {
    39.             castShadows = ShadowCastingMode.On,
    40.             layer = 1,
    41.             //material = mat,
    42.             mesh = mesh,
    43.             receiveShadows = true,
    44.             subMesh = 0
    45.         };
    46.  
    47.  
    48.         BlobAssetReference<Collider> boxCollider = Unity.Physics.BoxCollider.Create(new BoxGeometry()
    49.         {
    50.             BevelRadius = 0f,
    51.             Center = new float3(0, size.y / 2, 0),
    52.             Orientation = quaternion.identity,
    53.             Size = new float3(size.x, size.y, size.z)
    54.  
    55.         }, CollisionFilter.Default);
    56.  
    57.  
    58.         return CreateEntity(rm, boxCollider, mass, trans);
    59.     }
    60. ...
    61.