Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Script can't find Tagged GameObject

Discussion in 'Scripting' started by cate5171, Oct 15, 2020.

  1. cate5171

    cate5171

    Joined:
    Jan 5, 2020
    Posts:
    101
    Hello Everyone,
    I am making a menu thing where you can place a "block" from a Build Menu. I have made a script that disabled most of the objects on screen when placing it but when i try to place the object or cancel it, nothing responds and there are lots of errors (Object Reference not set to an instance of an object). The problem started when i entered this line of code into the script:
    Code (CSharp):
    1. MenuThing = GameObject.FindWithTag("MenuButton");
    The problem is that the script searches for a GameObject with the tag "MenuButton" but doesn't do anything and the whole script doesn't respond.
    How can i fix this? (The script can't find the tagged object)
    (Full Script):
    Code (CSharp):
    1. public Transform objectToPlace;
    2. private Camera gameCamera;
    3. private GameObject gameCamera3;
    4. private GameObject MenuThing;
    5.  
    6. void Update() {
    7.  
    8.       MenuThing = GameObject.FindWithTag("MenuButton");
    9.        gameCamera3 = GameObject.FindWithTag("CameraTag");
    10.        gameCamera = gameCamera3.GetComponent<Camera>();
    11.      Ray ray = gameCamera.ScreenPointToRay (Input.mousePosition);
    12.      RaycastHit hitInfo;
    13.  
    14.       if (Physics.Raycast (ray, out hitInfo)) {
    15.  
    16.            objectToPlace.position = hitInfo.point;
    17.  
    18.       if (Input.GetMouseButton(0))
    19.         {
    20.       MenuThing.SetActive(true);
    21.         objectToPlace.GetComponent<BuildingFollow2>().enabled = false;
    22.          objectToPlace.GetComponent<RotationBuilding>().enabled = false;
    23.      
    24.           }
    25.       if (Input.GetKey(KeyCode.Escape))
    26.       {
    27.         MenuThing.SetActive(true);
    28.         Destroy(gameObject);
    29.    
    30.     }
    31.   }
    32. }
    33. }
    34.  
     
    Last edited: Oct 15, 2020
  2. Sphinks

    Sphinks

    Joined:
    Apr 6, 2019
    Posts:
    267
    Is your menu(button) active if you do that call otherwise the method will return null, because it can only find active objects.
     
  3. cate5171

    cate5171

    Joined:
    Jan 5, 2020
    Posts:
    101
    The Button isn't active. Is there any way activate it another way?
     
  4. cate5171

    cate5171

    Joined:
    Jan 5, 2020
    Posts:
    101
    Fixed it by moving the deactivating to the same script and referencing there