Search Unity

OnClick Listener error "NullReference"

Discussion in 'Scripting' started by zapman502, Jan 17, 2022.

  1. zapman502

    zapman502

    Joined:
    Apr 13, 2020
    Posts:
    14
    So I made a function that creates buttons. I pass two arguments to it (gameobject name, button text), and it creates a UI button as a child of a scrollview's content object. I am trying to set a onClick() event to run a function, but I keep getting a null exception error [EDIT] when I press the button.
    Code (CSharp):
    1.  void MakeButton(string btnname, string _text)
    2.     {
    3.         //UnityAction unityAction;
    4.         //GameObject objButton = new GameObject(btnname);
    5.         //objButton.AddComponent<Button>();
    6.         //button.onClick.AddListener(() => { content.GetComponent<GameScript>().ChoiceMade(btnname); });
    7.  
    8.         GameObject objButton = DefaultControls.CreateButton(new DefaultControls.Resources()); //Creates the button
    9.         objButton.GetComponent<RectTransform>().sizeDelta = new Vector3(canvas.GetComponent<RectTransform>().sizeDelta.x, 100, 1); //Sets the button size
    10.         Button button = objButton.GetComponent<Button>(); //Gets the button component of button gameobject
    11.         button.name = btnname; //Changes name to input function argument btnname
    12.         objButton.GetComponentInChildren<Text>().fontSize = 40; //set fontsize
    13.         objButton.GetComponentInChildren<Text>().text = _text; //Set button text to second function argument
    14.         button.gameObject.transform.SetParent(content.transform); //Set button as child of scroll view content object with content size fitter/vertical layout components as well as this script.
    15.         button.onClick.AddListener(delegate { content.GetComponent<GameScript>().ChoiceMade(btnname); }); //Adds a on click event referencing the ChoiceMade function on same script???
    16.  
    17.  
    18.         //button
    19.         choiceList.Add(objButton); //ignore
    20.     }
    21.  
    22.     public void ChoiceMade(string name)
    23.     {
    24.         switch(name)
    25.         {
    26.             case "RedPill":
    27.                 storyText.text = "MEOOOOWw!!";
    28.                 break;
    29.         }
    30.         /*foreach(Button item in choiceList)
    31.         {
    32.             Destroy(item.gameObject);
    33.         }
    34.         choiceList.Clear();*/
    35.  
    36.    
    37.     }
    I tried to comment it as well as I can. So far, the buttons are indeed made when I call the function at runtime with the appropriate arguments given, and have their button components. Making the button seems to be perfectly fine, the issue is that I dont fully understand listeners and no other thread I found seemed to explain it in a way that I could understand. Is there no way to just essentially click the plus button on the button's OnClick() Event box in the inspector and add the gameobject and function from there, but in code? Would be nice if there was a OnClick().AddUnityEvent(arg gameobject, arg function) or something like that. But anyways, how would I go about making a function run as a listener?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    Don't get hung up on that. It's just a null reference.

    The answer is always the same... ALWAYS. It is the single most common error ever.

    Don't waste your life spinning around and round on this error. Instead, learn how to fix it fast... it's EASY!!

    Some notes on how to fix a NullReferenceException error in Unity3D
    - also known as: Unassigned Reference Exception
    - also known as: Missing Reference Exception
    - also known as: Object reference not set to an instance of an object

    http://plbm.com/?p=221

    The basic steps outlined above are:
    - Identify what is null
    - Identify why it is null
    - Fix that.

    Expect to see this error a LOT. It's easily the most common thing to do when working. Learn how to fix it rapidly. It's easy. See the above link for more tips.

    You need to figure out HOW that variable is supposed to get its initial value. There are many ways in Unity. In order of likelihood, it might be ONE of the following:

    - drag it in using the inspector
    - code inside this script initializes it
    - some OTHER external code initializes it
    - ? something else?

    This is the kind of mindset and thinking process you need to bring to this problem:

    https://forum.unity.com/threads/why-do-my-music-ignore-the-sliders.993849/#post-6453695

    Step by step, break it down, find the problem.

    Here is a clean analogy of the actual underlying problem of a null reference exception:

    https://forum.unity.com/threads/nul...n-instance-of-an-object.1108865/#post-7137032
     
    zapman502 and davidnibi like this.
  3. zapman502

    zapman502

    Joined:
    Apr 13, 2020
    Posts:
    14
    Thank you so much! Your answer and linked examples inspired me to look closer at the debug log and see where the errors were coming from. Turned out it was a problem with my list, and that I wasnt using the TextMeshPro namespace while attempting to edit a TMP object, so I was getting the wrong component. I love these types of answers that help one to actually LEARN the theory behind troubleshooting than just giving out code to copy.
     
    Lurking-Ninja and Kurt-Dekker like this.
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    Nice to be appreciated! I want everybody to learn how to fish.

    In that regard, rather than the sheet of honkin' long lines (line 8 to 15 above), you may want to air things out and break them up a bit more into areas of responsibility. Check out how I did it in this attached package. It's my reference way of cloning UI objects, populating their fields and hooking up delegates.
     

    Attached Files:

    zapman502 likes this.
  5. zapman502

    zapman502

    Joined:
    Apr 13, 2020
    Posts:
    14
    I will definitely dissect this in my free time. Thanks again! I really appreciate you going the extra mile to help.
     
    Kurt-Dekker likes this.