Instances from different scripts trigger error "Object reference not set to an instance of an object"

I have a small Unity project with 2 buttons in the scene, one is for playing music, and the other is to pause the music. I have 2 scripts, one attached to each.

There seems to be the “Object reference not set to an instance of an object” error when I try and access a public bool in the Playing script, from the Pausing script. I’ve made an Instance of the Playing script and I can’t think of anything else that needs to be done. Confusingly, I’ve done something similar to this for a previous simple project with no problem, so I’d appreciate any help on fixing this.

The script for the Play button:

using NUnit.Framework;
using System.Collections.Generic;
using UnityEngine;

public class PlayButton : MonoBehaviour
{
    public static PlayButton Instance;

    public bool playing;
    public bool pausing;
    public List<AudioSource> songs;
    public int index;
    public int tracks = 2;

   
    void Start()
    {
        index = Random.Range(0, tracks);
    }

    
    void Update()
    {
        if(pausing == true)
        {
            songs[index].Pause();
        }
    }

    public void Clicked()
    {
        if(playing == false)
        {
            playing = true;
            songs[index].Play();
        }

        else if(playing == true)
        {
            playing = false;
            songs[index].Pause();
        }
    }

From what I can tell, all this code works as it should.

Here’s the script for pausing:

using UnityEngine;
using System.Collections.Generic;

public class pauseButton : MonoBehaviour
{

	public void Pause()
	{
		PlayButton.Instance.pausing = true;
	}

In Unity it says the error is on line 9 of the Pausing script. Thank you for any help :slight_smile:

It seems you want to have the PlayButton as a singleton but you haven’t set the static Instance anywhere in the PlayButton script.

1 Like

Thank you for replying! In the script I previously provided, I’ve written “public static PlayButton Instance” in the PlayButton script, line 7. Is that what you thought was missing? :slight_smile:

No, read my comment again, you have the public static PlayButton Instance but you haven’t initialized it anywhere in your script. You need to initialize reference type variables before using them or else they will be null.