Hey! I am trying to script a button, and keep getting a NullReferenceException error in Unity. I am following examples, and can’t find what I am doing wrong. Any help would be greatly apprecipated!
Did you assign the ButtonThree reference in the inspector? A NullReferenceException basically tells you that some object reference (ie the Button object) was not set, but you are trying to use it.
Also the line in the error message does not match the lines of your script. Did you by any chance remove empty lines between the screenshots? The line in question should be 20 or 21, there is no code at 22.
In the future please use code tags instead of screenshots tho
Thanks for the reply, yes you are right the error was in Line 20 (Line 9 below). I am not sure why this is not set, the script has been added to the GameObject, which has been added as an OnClick() event to the desired button. Here is the embedded code:
public class negativePoint : MonoBehaviour
{
public Button ButtonThree;
// Start is called before the first frame update
void Start()
{
Button btn3 = ButtonThree.GetComponent<Button>();
btn3.onClick.AddListener(NegativeClick);
}
Did you drag the button script into the ButtonThree field in the inspector of your negativePoint script?
Edit: Also ButtonThree is already type Button, no need to get its Button component. Not sure if that’s even possible, so maybe that’s a problem as well. Check what i wrote above before tho.
Some notes on how to fix a NullReferenceException error in Unity3D
- also known as: Unassigned Reference Exception
- also known as: Missing Reference Exception
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.
It would not let me drag any button type into that box. I think you are right, it works much better when I don’t access the Button component and just add the function to the button in the Inspector. Thanks!
Thanks! That also helps a lot