Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Components created with [GenerateAuthoringComponent] are in another world

Discussion in 'Entity Component System' started by flatterino, Jun 8, 2020.

  1. flatterino

    flatterino

    Joined:
    Jan 22, 2018
    Posts:
    17
    Hello,

    I have a Component with the
    [GenerateAuthoringComponent]
    attribute. This component is assigned to an empty GameObject with the Convert To Entity script. The component holds a single integer field, called
    integerField
    , which is editable from the Editor.

    I have a System that is supposed to read that integer on startup. However, I can't seem to able to access that integer. I'm using
    GetSingleton<MyComponent>
    but I get an error on startup saying that there are no instances of such component.
    Code (CSharp):
    1. // find the component which stores my integer (editable on Editor, since it's an authoring component)
    2. EntityQuery query = this.World.EntityManager.CreateEntityQuery(ComponentType.ReadOnly<MyComponent>());
    3.  
    4. // get the integer field we're interested in
    5. int theValue = query.GetSingleton<MyComponent>().integerField;
    Specifically, the exception says "GetSingletonEntity() requires that exactly one exists but there are 0".

    I believe my problem is that the Component that I'm trying to access to read that integer "lives" in the
    DefaultGameObjectInjectionWorld
    world, since it was created using
    [GenerateAuthoringComponent]
    , and my system "lives" in a different world (the default one?), but I can't seem to overcome this.

    Any ideas? Thank you.
     
    Last edited: Jun 8, 2020
  2. brunocoimbra

    brunocoimbra

    Joined:
    Sep 2, 2015
    Posts:
    677
    Are you trying to access it on OnCreate? Because OnCreate will be called before any scene is loaded.

    What you want to do is add an
    RequireSingletonForUpdate(query)
    in OnCreate, and use the OnStartRunning to get the integerField.
     
    flatterino likes this.
  3. flatterino

    flatterino

    Joined:
    Jan 22, 2018
    Posts:
    17
    That worked perfectly, @brunocoimbra. Thank you!
     
    brunocoimbra likes this.