Hi!
In my code I have SettingsComponent fields of which I will use in many systems (>2) and this SettingsComponent doesn’t even changing because it’s just readonly data. It will be more convenient if there’ll be way to create static DataComponent with this settings and just get them from the code in future.
Is there any way to make static data component in ECS 1.0?
1 Answer
1You can use singleton components for this:
Here is how you will access this settings component in any system:
var settings = SystemAPI.GetSingleton<SettingsSystem.Data>();
Here is how to create such settings component:
using Unity.Entities;
using Unity.Collections;
[Unity.Burst.BurstCompile]
[UpdateInGroup( typeof(InitializationSystemGroup) , OrderFirst=true )]
public partial struct SettingsSystem : ISystem
{
public struct Data : IComponentData
{
public float Volume;
public int Difficulty;
}
[Unity.Burst.BurstCompile]
public void OnCreate ( ref SystemState state )
{
Entity singleton = state.EntityManager.CreateEntity();
state.EntityManager.AddComponent<Data>( singleton );
SystemAPI.SetSingleton( new Data{
Volume = 1.0f ,
Difficulty = 1 ,
} );
state.Enabled = false;
}
[Unity.Burst.BurstCompile]
public void OnDestroy ( ref SystemState state )
{
if( SystemAPI.TryGetSingletonEntity<Data>(out Entity singleton) )
{
state.EntityManager.DestroyEntity( singleton );
}
}
}
Alternatively:
Systems & Jobs can access static unmanaged struct fields, if you ever need that. Not a good way to store settings but constants - why not.