Access regular transform from ECS

Hello everyone! I am new to ECS and I am struggling to get reference to a regular Camera transform from ECS system.

I want to control the Camera transform or Light transform from the ECS ISystem script.

Please help if you know the solution.

You can use entityManager.AddComponentObject(obj) to create an Entity that references any object, Transform included. It’s good idea to reference a “tag” type object (Camera or Light component in this case) alongside it as well so this Entity will be easier to distinguish (EntityQuery) from other similar entities.

https://docs.unity3d.com/Packages/com.unity.entities@1.2/api/Unity.Entities.EntityManager.AddComponentObject.html

This ObjectsToEntity will create you an Entity that will host references to anything that you drop into it’s Objects field. It will also destroy this entity once ObjectsToEntity is destroyed.

ObjectsToEntity.cs

using UnityEngine;
using Unity.Entities;

public class ObjectsToEntity : MonoBehaviour
{
    [SerializeField] Object[] _objects;
    Entity _entity;
    void Awake ()
    {
        var em = World.DefaultGameObjectInjectionWorld.EntityManager;
        _entity = em.CreateEntity();
        foreach( var obj in _objects )
        {
            em.AddComponentObject( _entity , obj );
        }
    }
    void OnDestroy ()
    {
        var em = World.DefaultGameObjectInjectionWorld.EntityManager;
        if( em.Exists(_entity) ) em.DestroyEntity( _entity );
    }
}

Drag&Drop both Camera component and Transform object into Objects field.

MonoBehaviour Inspector:
image

Entity Inspector:
image

Query for this Entity in your ISystem, access it’s corresponding Transform and be merry

using UnityEngine;
using Unity.Entities;
using Unity.Collections;

public partial struct MerrySystem : ISystem
{
    EntityQuery _query;
    public void OnCreate ( ref SystemState state )
    {
        _query = state.EntityManager.CreateEntityQuery( typeof(Camera) , typeof(Transform) );
        state.RequireForUpdate( _query );
    }
    public void OnDestroy ( ref SystemState state )
    {
        _query.Dispose();
    }
    public void OnUpdate ( ref SystemState state )
    {
        var em = state.EntityManager;
        foreach( Entity entity in _query.ToEntityArray(Allocator.Temp) )
        {
            Vector3 pos = em.GetComponentObject<Transform>(entity).position;
            Debug.DrawLine( pos , new Vector3(pos.x,0,pos.z) , Color.magenta );
        }
    }
}