Search Unity

They say not to use GameObject.find, but what if I need to reference from a prefab instance?

Discussion in 'Scripting' started by unity_94d33m, Mar 18, 2019.

  1. unity_94d33m

    unity_94d33m

    Joined:
    Sep 11, 2018
    Posts:
    20
    Like a bullet prefab that has many instances and each one needs to have a reference to GameManager, in that case in the Start() function of that prefab I have to do :
    void Start ()
    {
    GameObject gameControllerObject = GameObject.FindGameObjectWithTag ("GameController");
    if (gameControllerObject != null)
    {
    gameController = gameControllerObject.GetComponent <Done_GameController>();
    }
    if (gameController == null)
    {
    Debug.Log ("Cannot find 'GameController' script");
    }
    }

    Is this .find unavoidable ?
     
  2. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    Lots of ways to avoid it, but first of all, if you only call it once in a while it's ok. (although I personally never use it)

    One solution (that I use way too much) to this is the singleton pattern, have your gameController have a public static GameController variable in the GameController class itself and set it to itself on OnEnabled/Awake/Start, then you can access it though every where in the project, but look out for all sort of gotchas with it, google will be your friend for that, lol.

    Code (CSharp):
    1. public class GameController {
    2.  
    3. public static GameController instance;
    4.  
    5. void Awake(){
    6. instance = this;
    7. }
    8. }
    9.  
    10. //then you can say in other parts of the project stuff like
    11.  
    12. public class Bullet {
    13.  
    14. GameController gc;
    15.  
    16. void Shoot(){
    17. gc = GameController.instance;
    18. //other stuff
    19. }
    20.  
    21. }
    *can also not cache the ref. and just do what you want directly to it when done, which I also do a lot.
     
    unity_94d33m likes this.
  3. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    2,445
    In short, the code that is instantating the prefab should also do setup of that prefab. Position it, tell it what manager object it should register with, etc.
     
    ThermalFusion likes this.