Search Unity

Question how to get an singleton entity from a monobehavior?

Discussion in 'Entity Component System' started by Salmakis, Nov 30, 2022.

  1. Salmakis

    Salmakis

    Joined:
    May 14, 2018
    Posts:
    15
    hey, i try to acess an IComponent thingy from a MonoBehavior to set some options for my entities.

    it works in my system on the OnUpdate with:
    Code (CSharp):
    1. LivingControllerData lcd = SystemAPI.GetSingleton<LivingControllerData>();
    now i want to put there some settings that the system can then use.

    so i wanted to acces this one entity (its LivingControlData) in a monobehavior to set stuff on key presses.

    i did it with the following in the update method of the monobehavior.
    Code (CSharp):
    1.  
    2. EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
    3. LivingControllerData lcd = entityManager.UniversalQuery.GetSingleton<LivingControllerData>();
    4.  
    but it throws:
    InvalidOperationException: GetSingleton() requires that exactly one entity exists that matches this query, but there are 14.

    but no, there are not 14 entities with a "LivingControllerData" IComponentData, there is only one (it was created in the baker).


    there is only one, not 14.

    what am i doing wrong here?
    is this the wrong approach in general to access that entity (its component) from a monobehavior?

    im using:
    using 1.0.0-pre.15
     
  2. Fribur

    Fribur

    Joined:
    Jan 5, 2019
    Posts:
    136
    you can create an EntityQuery, and get the Singleton (or the singleton entity) from that Query:
    Code (CSharp):
    1. EntityManager _entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
    2. EntityQuery colorTablesQ = _entityManager.CreateEntityQuery(new ComponentType[] { typeof(ColorTables) });
    3. colorTablesQ.TryGetSingletonEntity<ColorTables>(out Entity colorTablesEntity)
    4.  
     
    Ksanone, 1163r0, Opeth001 and 2 others like this.
  3. Salmakis

    Salmakis

    Joined:
    May 14, 2018
    Posts:
    15
    ty, that was then not so complicated at all.