0

I have a Unity problem where I am trying to play sound when addScore() function starts using dingSFX.Play();, but instead I get the following error: ArgumentNullException: Value cannot be null.

I am using Audio Source component that I added into my Inspector tab where also my script(LogicScript.cs) is. I also added the AudioClip into Audio Source.

LogicScript.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class LogicScript : MonoBehaviour
{

    public int playerScore;
    public Text scoreText;
    public GameObject gameOverScreen;
    public AudioSource dingSFX;


    
    [ContextMenu("Increase Score")]
    public void addScore(int scoreToAdd)
    {
        playerScore = playerScore + scoreToAdd;
        scoreText.text = playerScore.ToString();

        dingSFX.Play();    // this does not work

      
    }

    public void restartGame()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }

    public void gameOver()
    {
        gameOverScreen.SetActive(true);
    }
} 
Pleinair
  • 437
  • 9
  • 21
  • 1
    sounds like `dingSFX` doesn't have any `clip` assigned so it tries to start playing .. well nothing ;) – derHugo May 10 '23 at 16:09
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Jay May 10 '23 at 16:40

1 Answers1

0

You have to assign an audio source to an audio source, not an audio clip to an audio source.

Create an empty gameobject, call it whatever you want, add an audio source component to it, drag the clip into the clip field of the audio source, and drag the audio source containing gameobject to the dingSFX on your script.