I cant solve the error: Object reference not set to an instance of an object

Hello I have this error: NullReferenceException: Object reference not set to an instance of an object
ButtonController.Start () (at Assets/Scripts/Buttons/NewGameScripts/ButtonController.cs:22)
And I just cant solve it, it is making me mad.
The thing is that once I start the game it works fine but as soon as I press de ConfirmButtom that error apear.
Here i have de script if someone could take the time to hep I pretty much apreciate it.

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class ButtonController : MonoBehaviour
{
    public Button J2;
    public Button J3;
    public Button J4;

    public Vector3 normalScale = new Vector3(1, 1, 1);
    public Vector3 selectedScale = new Vector3(1.2f, 1.2f, 1.2f);
    public float animationDuration = 0.2f;
    public ConfirmButtonController confirmButtonController;
    public GameController gameController;
    public int NumJug = 0;
    private Button selectedButton;

    void Start()
    {
        // Asignamos los listeners a los botones especĂ­ficos
        J2.onClick.AddListener(() => OnButtonClick(J2));
        J3.onClick.AddListener(() => OnButtonClick(J3));
        J4.onClick.AddListener(() => OnButtonClick(J4));
    }

    void OnButtonClick(Button clickedButton)
    {
        if (selectedButton != clickedButton)
        {
            if (selectedButton != null)
            {
                // Detenemos la animaciĂłn anterior si existe en el GameController
                gameController.StartRestoreNormalScaleAnimation(selectedButton);
            }

            // Escalamos el botón recién seleccionado en el GameController
            gameController.StartScaleAnimation(clickedButton, selectedScale);
            selectedButton = clickedButton;
            confirmButtonController.EnableConfirmButton();
        }
        // Asignamos el valor correspondiente a NumJug
        if (clickedButton == J2)
        {
            NumJug = 2;
        }
        else if (clickedButton == J3)
        {
            NumJug = 3;
        }
        else if (clickedButton == J4)
        {
            NumJug = 4;
        }
        PlayerPrefs.SetInt("NumJug", NumJug);
    }
}

I think I have all the objects placed on the inspector so I just dont know what to do anymore.
image

It pretty much means something on line 22 is null. Most likely J2. Did you forget to assign the button via the inspector? Or do you have an extra instance somewhere in the scene that you haven’t noticed?

I already Edit the post so that you can see I think they are but still gave me the error

That leads to my second point: is there an instance somewhere in a scene/on a prefab you haven’t noticed?

Some simple debugging can lead you to answer that. Such as throwing a debug.log that supplies an object for context into the method where it happens:

void Start()
{
    Debug.Log($"Starting {name}!", this);
    J2.onClick.AddListener(() => OnButtonClick(J2));
    J3.onClick.AddListener(() => OnButtonClick(J3));
    J4.onClick.AddListener(() => OnButtonClick(J4));
}

when I start with de Debug.log It gave me this:

Im gona put a image of the Scene objects on the post so that you can see it

didnt let me jaja so here it is:

image

Right, so you get two logs. Is that expected? If not, click on the logs, and they’ll ping the object in the heirachy. Then either fix or remove the erroneous component. No point pasting your heirarchy.

okey, when I select the first one it ping the ButtonController but the second one didnt ping anything so I assume there is the problem. But I still have no idea how to solve it.
I mean: when the progran start the first log apear, thats the one that ping the buttoncontroller
Then when i click on the confirmbutton to go to the next scene, the second log apear, that is the one that not ping anything.
The program continue to the next scene but pauses cause the error.

So perhaps the component that’s missing the references is on a game object called ButtonController in the other scene? Or is there any DontDestroyOnLoad shenanigans going on here?

What’s the code for the Confirm button?

Bottomline is somewhere there is a ButtonController component missing these references. You just need to find and fix that.

I dont know realy I mean, the line that it reference is the line for the J2 buttom, but that buttom is already on the inspector.
Here is the code for the confirmbutton:

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class ConfirmButtonController : MonoBehaviour
{
    public Button confirmButton;
    public CanvasGroup confirmButtonCanvasGroup;

    void Start()
    {
        // Al inicio, desactivamos el botĂłn de confirmaciĂłn
        DisableConfirmButton();

        // Asignamos un listener al botĂłn para manejar el clic
        confirmButton.onClick.AddListener(OnConfirmButtonClick);
    }

    public void EnableConfirmButton()
    {
        // Habilita el botĂłn de confirmaciĂłn
        confirmButton.interactable = true;
        confirmButtonCanvasGroup.alpha = 1f; // Opacidad completa (sin transparencia)
    }

    public void DisableConfirmButton()
    {
        // Deshabilita el botĂłn de confirmaciĂłn
        confirmButton.interactable = false;
        confirmButtonCanvasGroup.alpha = 0.5f; // Opacidad reducida (transparencia)
    }

    public void OnConfirmButtonClick()
    {
        // AquĂ­ es donde manejamos el clic en el botĂłn de confirmaciĂłn
        // En lugar de cambiar la escena, no hacemos nada adicional
        // El botón simplemente mantendrá su efecto de opacidad y no hará más acciones
    }
}

Looking at it null, if J2 wasn’t assigned, it would actually be throwing a Missing Reference Exception, though it’s a bog-standard null-reference exception. So perhaps it’s not J2 that’s null, but something else. The only other thing that could be null is the onClick delegate? That would be super weird if it was.

Nonetheless, you should still test this out. Probably like so:

void Start()
{
    Debug.Log("J2 Exists: " + J2 != null, this);
    Debug.Log("J2 onClick Exists: " + J2.onClick != null, J2);
	
    // etc etc
}

here´s the result:

The problem by itself its weird jaja the thing is, the game worked just fine some hours ago. The last change that I made before a notice the error was when I put the:

PlayerPrefs.SetInt("NumJug", NumJug);

But I tried the program without it and it gave me same error.

O and another fun thing is that the 24 line that is referencing is the line for the:

Debug.Log("J2 onClick Exists: " + J2.onClick != null, J2);

So now I´m more than confused jaja

I think the most important thing is that ButtonController.Start is getting called twice, so there are at least two instances of the component somewhere.

Are you loading into a different scene, or the same scene? If you’re loading into another scene, have you investigated the other scene?

1 Like

OMG it was a so simple problem but I didnt think of it.
Yes I was loading to another scene and in that scene I had 2 ButtomControllers, I just eliminate one of them cause I dont have any idea how that duplicate like that.
Thanks so much for your help bro and Im sorry that I was searching for the problem in the wrong place.
Now it work just fine thanks men.

1 Like