How to set a singleton in an Authoring Component and then Get it. (Solved)

I’m trying to create some singletons using the conversion workflow as configuration data, and read from them in different systems. I’ve tried everything I can think of, but the entity query in the system just can’t find anything.

This is my code in the authoring to do the conversion.

        public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
        {
            dstManager.SetComponentData(entity, new CameraConfigSingleton {defaultFOV = Camera.main.fieldOfView} );
        }

I dragged the authoring monobehaviour onto an empty gameobject and converted, looks as expected.

Yet when I try to call GetSingleton, or do any sort of query for the entity it can’t find it.

        protected override void OnCreate()
        {
            startingZoom = GetSingleton<CameraConfigSingleton>().defaultFOV;
        }

“InvalidOperationException: GetSingleton<DataComponents.Singletons.CameraConfigSingleton>() requires that exactly one DataComponents.Singletons.CameraConfigSingleton exist that match this query, but there are 0.”

I’ve tried all sorts to get it to work, and it even looks similar to what i’ve seen in the samples repo but, I just can’t figure out whats wrong with it. Any help is appreciated!

Put some debug.log messages down and see what executes earlier. I guess the OnCreate happens earlier then the monobehaviour conversion

1 Like

That was my guess, but I tried waiting to get the singleton until I press a key in Update just to test it, but no luck.

OnCreate should not query for entities, for any auto-created system it will happen before any conversion or scene is loaded. Use RequirieSingletonForUpdate and then query the singleton on the OnStartRunnning if you want it to be a one-time thing

1 Like

Thanks so much, that fixed it!

Looks like you were correct about the OnCreate happening earlier, must have made a mistake when i tried to test for that previously.

This is not always the case. If you use a default bootstrap 100% but I’ve found creating all your setting entities etc before systems are created is a very useful pattern for setting management, save files and backwards compatibility.
Anyway I recently discussed my current lifecycle setup here

https://discussions.unity.com/t/832555/6

Yeah, I was referring to the default bootstrap. For easier code reusability between projects, I tend to always consider the default one as it makes it easier to create standard workflows for other developers too.