I'm learning unity and I'm trying to change the volume of the background music when the game starts but can't access script where the sound is playing (game scene) from settings menu (settings scene).
There is always an error in settings scene line that says
"BGMusicScript = GameObject.FindGameObjectWithTag("BGMusic").GetComponent();" which says "Object reference not set to an instance of an object".
Settings scene:
public class SettingsMenuLogic : MonoBehaviour
{
public TMP_Dropdown resolutionDropdown;
Resolution[] resolutions;
public Slider BGMusicSlider;
public GameObject backgroundMusicGameObject;
public BackgroundMusicScript BGMusicScript;
void Start()
{
resolutions = Screen.resolutions;
resolutionDropdown.ClearOptions();
List<string> options = new List<string>();
int currentResolutionIndex = 0;
for(int i = 0; i < resolutions.Length; i++)
{
string option = resolutions[i].width + " x " + resolutions[i].width;
options.Add(option);
if (resolutions[i].width == Screen.currentResolution.width && resolutions[i].height == Screen.currentResolution.height)
{
currentResolutionIndex = i;
}
}
resolutionDropdown.AddOptions(options);
resolutionDropdown.value = currentResolutionIndex;
resolutionDropdown.RefreshShownValue();
BGMusicScript = GameObject.FindGameObjectWithTag("BGMusic").GetComponent<BackgroundMusicScript>();
if (!PlayerPrefs.HasKey("BGMusicVolume"))
{
PlayerPrefs.SetFloat("BGMusicVolume", 1);
loadBGVolume();
} else
{
loadBGVolume();
}
}
public void setResolution(int resolutionIndex)
{
Resolution resolution = resolutions[resolutionIndex];
Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreen);
}
public void changeBGVolume()
{
BGMusicScript.BGMusic.volume = BGMusicSlider.value;
saveBGVolume();
}
public void saveBGVolume()
{
PlayerPrefs.SetFloat("BGMusicVolume", BGMusicSlider.value);
}
public void loadBGVolume()
{
BGMusicSlider.value = PlayerPrefs.GetFloat("BGMUsicVolume");
}
public void setQuality(int qualityIndex)
{
QualitySettings.SetQualityLevel(qualityIndex);
}
public void setFullscreen(bool isFullscreen)
{
Screen.fullScreen = isFullscreen;
}
}
Script from game scene:
public class BackgroundMusicScript : MonoBehaviour
{
public BirdScript bird;
public AudioSource BGMusic;
// Start is called before the first frame update
void Start()
{
bird = GameObject.FindGameObjectWithTag("Bird").GetComponent<BirdScript>();
BGMusic = GetComponent<AudioSource>();
BGMusic.volume = PlayerPrefs.GetFloat("BGMusicVolume");
}
// Update is called once per frame
void Update()
{
if(bird.birdIsAlive == false)
{
BGMusic.Stop();
}
}
}
Tried finding a tutorial on Google but to no avail, I hope someone here can help.