Search Unity

GameObject.FindGameObjectWithTag in JobComponentSystem

Discussion in 'Entity Component System' started by RoughSpaghetti3211, May 23, 2019.

  1. RoughSpaghetti3211

    RoughSpaghetti3211

    Joined:
    Aug 11, 2015
    Posts:
    1,708
    quick question. Is this allowed in a JobComponentSystem or is there a better way of doing this.

    Code (CSharp):
    1.        
    2.     protected override void OnCreate()
    3.     {
    4.          // Get reference
    5.          _gameSettings = GameObject.FindGameObjectWithTag("tagGameSettings").GetComponent<GameSettings>();
    6.          if (_gameSettings == null)
    7.              throw new InvalidOperationException("_gameSettings not found");
    8.     }
    9.  
     
  2. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    5,203
    Systems are by default created when the player boots up and destroyed when it shuts down.
    Scenes, come and go, so this setup doesn't make much sense and is not ECS idiomatic.

    That said, in specific cases it and if you control world creation for your game specifically it is possible. But i wouldn't recommend it...
     
    GameDeveloper1111 likes this.
  3. RoughSpaghetti3211

    RoughSpaghetti3211

    Joined:
    Aug 11, 2015
    Posts:
    1,708
    Ok thanks for the quick reply
     
  4. Sarkahn

    Sarkahn

    Joined:
    Jan 9, 2013
    Posts:
    440
    If you do want to do this you can use SceneManager.sceneLoaded callback and FindObject from there since objects might not even be initialized in OnCreate.

    I was using this method to be able to tweak settings in the inspector and then pass those settings off to a system in the way they are here. I'm curious what you would recommend instead for that, or is this our best option for now?
     
  5. RoughSpaghetti3211

    RoughSpaghetti3211

    Joined:
    Aug 11, 2015
    Posts:
    1,708
    I was going to try an use ConvertToEntity to get my gameSetting from a gameObject and convert it to entity data. Maybe this is not the right way either ?
     
  6. Sarkahn

    Sarkahn

    Joined:
    Jan 9, 2013
    Posts:
    440
    When I tried this on the previous release my system was not able to find my converted entity - meaning the conversion process doesn't happen before OnCreate. I guess you can create an EntityQuery specifically for your settings entity or use GetSingleton every time you need to access it, seems a little akward though.
     
  7. RoughSpaghetti3211

    RoughSpaghetti3211

    Joined:
    Aug 11, 2015
    Posts:
    1,708
    Im not sure I understand do you have a small code snipped I can look at for your idea of converting game object to entity and then using GetSingelton . First time ive heard of GetSingelton method
     
  8. Sarkahn

    Sarkahn

    Joined:
    Jan 9, 2013
    Posts:
    440
    It's a method on ComponentSystem/JobComponentSystem. You can just call it from inside OnUpdate