Hi!
In my project I have multiple cameras with different values of Field Of View which can also be dynamically changed. Also I need to switch active camera (deactivate one and activate another during the runtime). All of this makes me access these authoring Camera components so I can manipulate their values.
Is there ways to access authoring components of specific GameObjects from ECS Systems?
P.S. Obviously I can’t just use Singleton link because cameras more than one
1 Answer
1
I answered very similar question here:
ObjectsToEntity.cs is your authoring-like component that maintains an Entity with references to any UnityEngine.Object you want.
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 );
}
}
In short, this is how accessing Camera component would look like on ECS side:
Camera cam = EntityManager.GetComponentObject<Camera>(entity);
ISystem example
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 );
}
}
}
→ More details in the linked thread.