Search Unity

What is a best practice for caching a GameObject to be reusable/shared by many other GameObjects?

Discussion in 'Scripting' started by nopelater, Jun 27, 2018.

  1. nopelater

    nopelater

    Joined:
    Jun 14, 2018
    Posts:
    4
    For example, I have three GameObjects - Player, Treasure, Guard.

    The Player makes a reference to Treasure, because when it collides with Treasure, it destroys it. The Guard also makes a reference to Treasure, because it is placed within the vicinity of the Treasure. (This is just an example scenario of two GameObject's making a reference to one.)

    My point, is instead of making two GameObject.Find calls (which I heard are relatively expensive), I declare them static in another class, let's say called Globals.cs (public static GameObject target = GameObject.Find("Target")) and then Globals.target to fetch it.

    I'm wondering if this is a good idea, or is there a better way to go about this?
     
  2. WheresMommy

    WheresMommy

    Joined:
    Oct 4, 2012
    Posts:
    890
    So you are telling us, you only have one player, one treasure and one guard in your game at one time? Because that's, what static means, you only gonna have ONE of those things at the same time. If you can tell us your environment, we can continue help you :)
     
    Kiwasi likes this.
  3. nopelater

    nopelater

    Joined:
    Jun 14, 2018
    Posts:
    4
    There can be multiple instances of guards and targets. One player.
     
  4. WheresMommy

    WheresMommy

    Joined:
    Oct 4, 2012
    Posts:
    890
    Then you should go for static with player but not for the rest. So, if you give the player something like
    Code (CSharp):
    1. public Player player;
    2.  
    3. void Start()
    4. {
    5. player = this;
    6. }
    and have a global.cs file with something like
    Code (CSharp):
    1. public Global global;public Treasure currentTreasure;
    2. public Guard currentGuard;
    You could add the treasure to it with the oncollisionenter for example
    Code (CSharp):
    1. void OnCollisionEnter(Collision collision)
    2.     {
    3.         Global.global.currentTreasure = this;
    4.     }
    Just a quick sum up of what I would do or where to start.
     
  5. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Static is for stuff that's truly global, and even then it should be used with caution. Things like 'What is the current game volume?', 'What system is the user playing on?' and so on.

    For most game play stuff, inspector references do the job fine.