Search Unity

basic question on onClick for panels

Discussion in 'Scripting' started by overthrowrobotics, Aug 3, 2015.

  1. overthrowrobotics

    overthrowrobotics

    Joined:
    Jun 19, 2015
    Posts:
    47
    I have some buttons on panels that I'm using as a menu. I have a panel called mainMenu with a button called fightButton and On Click for fightButton set to mainMenu.menuChange with the string fightMenu. I have another panel called fightMenu.

    I'm expecting "fightMenu" to be passed into string menuName, find the gameobject called fightMenu (panel). Then set the first panel not active and the menu fightMenu as the active. When I click the fightButton I get Object reference not set to an instance of an object on line 13 which is the (if mainMenuButton.name == "fightMenu") line. If it didn't find the object why wouldn't it give an error on the previous line?

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using UnityEngine.UI;
    4.  
    5. public class mainMenu : MonoBehaviour {
    6.  
    7.     public GameObject mainMenuPanel;
    8.     GameObject mainMenuButton;
    9.  
    10.     public void menuChange(string menuName) {
    11.  
    12.         mainMenuButton = GameObject.Find (menuName);
    13.  
    14.         if (mainMenuButton.name == "fightMenu") {
    15.             print ("fight button pressed");
    16.             mainMenuPanel.SetActive(false);
    17.  
    18.         }
    19.     }
    20. }
    21.  
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Find returns null if the object is not found. Thus the error later.

    This all seems like there is some deeper code structure issues here. Find is generally to be avoided. And there are often better solutions then checking a GamObjects name.