Search Unity

Do we have to use GameObject.GetComponent("") every frame

Discussion in 'Scripting' started by vanhouten777, Jul 25, 2014.

  1. vanhouten777

    vanhouten777

    Joined:
    Apr 30, 2012
    Posts:
    138
    Hi,

    Do we have to use GameObject.GetComponent("") every frame to get the latest data or is it a pointer to the component?
    Regards,
    vanhouten777.
     
  2. vanhouten777

    vanhouten777

    Joined:
    Apr 30, 2012
    Posts:
    138
    Hi,

    Same way do we have to use GameObject.Find("") every frame to get the latest data of the game object or is it a pointer to the game object?
    Regards,
    vanhouten777.
     
  3. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    if it's for something that isn't going to be changed do it in the start function and cache the result in a variable. It's a pointer.
     
  4. vanhouten777

    vanhouten777

    Joined:
    Apr 30, 2012
    Posts:
    138
    Hi LeftyRighty,

    Thanks for the reply.
    Regards,
    vanhouten777.
     
  5. Arowx

    Arowx

    Joined:
    Nov 12, 2009
    Posts:
    8,194
    Or if it's not dynamic you can setup a public GameObject variable in the script that needs it set it in the editor.

    Or you can set up a script on the Object with a static public use variable that records the gameobject on start which can then be accessed at any time.

    Code (CSharp):
    1. class Singleton()
    2. {
    3. public static GameObject use;
    4.  
    5. public void Awake()
    6. {
    7.    use = gameObject;
    8. }
    9. }
    Then you can just write Singleton.use to access this game object. This is best used where there is only one of these objects in your game, for example Manager classes or core Game components.