Search code examples
c#unity-game-enginegameobject

How to: Get instance of gameObject


Looking to get an instance of this game object so I can successfully use .enabled to hide it in a scene.

PlayPortalLoginButton loginButton = gameObject.GetComponent<PlayPortalLoginButton>();

Fairly new to C# and I believe I am close to achieving my goal with the line above. What needs changed? Want to understand how to correctly do this.


Solution

  • Here is one way you could find a component on a GameObject in the scene, where "PortalLoginButton" is the name of the GameObject as seen in the editor:

    var loginButton = GameObject.Find("PortalLoginButton");
    loginButton.enabled = false;
    

    However, GameObject.Find("...") searches the name of every GameObject in the scene, and this is not usually the best way to reference a GameObject since it is not very efficient. So make sure not to use GameObject.Find("...") or similar function calls in the Update() function because it will execute every frame and slow your game down. If the GameObject is not instantiated while the game is running, it is usually better to make a global reference to any GameObject or Component that you use in your script and then drag-and-drop the GameObject with the Component you are looking for into the field in the editor. Alternatively, you can use GameObject.Find("...") in the Start() or Awake() functions to store a reference to the GameObject that you are looking for, so that the search only happens once at the start of your game.

    Here is an example of how to store the reference in global field (it will show up in the editor and you can drag-and-drop the GameObject into it). The differences between using a public field vs a private field are explained in the comments (you can decide on using public or private):

    // By default, private fields are not viewable in the editor,
    // but the [SerializeField] attribute, placed before
    // the field declaration, allows them to be visible.
    [SerializeField]
    private GameObject loginButtonPrivateReference;
    // If you need to access loginButton from another script, 
    // you can make it a public field.
    // Public fields are viewable in the editor by default.
    public GameObject loginButtonPublicReference;
    

    Here is an example of how you can use GameObject.Find("...") in the Awake() function:

    private GameObject loginButton;
    
    private void Awake() {
        loginButton = GameObject.Find("PortalLoginButton");
    }
    

    If you need to search for GameObjects in your scene by type or by tag name, see the GameObject documentation here for more information. Searching by type is less efficient and searching by tag is more efficient than searching by name because type searches check each component on each GameObject, and tag searches search only an organized GameObject subset.