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

Resolved How to access data that is stored in a GameObject from a system (in or outside of the Foreach)

Discussion in 'Entity Component System' started by OMGeeky, Jan 29, 2022.

  1. OMGeeky

    OMGeeky

    Joined:
    Sep 5, 2018
    Posts:
    17
    Good Day,
    I have a problem accessing data that is stored as a field on a GameObject MonoBehaviour from inside a SystemBase.
    On my GameObject I have a list of some values that get changed sometimes by other GameObjects/MBs and I need to access this data from a few Systems (readonly in this case) to filter inside the Foreach for some data.
    I just cant seem to figure out how to access data from a MonoBehaviour inside of a System.

    I also came across GameObjectEntity but couldn't figure out how it should be used.
     
  2. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,647
    The easiest way is to simply attach the MonoBehaviour to the entity.

    EntityManager.AddComponentObject(entity, myMonoBehaviour);


    Then you can just query it in an Entities.ForEach

    Code (CSharp):
    1. Entities.ForEach((MonoBehaviour mb) =>
    2. {
    3.     var myValue = mb.Value;
    4. })
    5. .WithoutBurst().Run();
     
    DevViktoria likes this.
  3. OMGeeky

    OMGeeky

    Joined:
    Sep 5, 2018
    Posts:
    17
    I guess that works for me, thanks!

    Just out of curiosity, how would I go about it if I need the same data in a lot of entities and some of them have a GameObject already attached?