Reputation: 449
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);
}
}
Upvotes: 0
Views: 751
Reputation: 36
Like what others mentioned, the script itself has no error. The only reason why this doesn't work is because you didn't assign your audio source to your script in the inspector. Which means that your script couldn't find an audio source. Check out this video for an example.
Since you've mentioned that the script and the audio source are both on the same gameObject, you can try:
void Start()
{
dingSFX = GetComponent<AudioSource>();
}
This way you get reference via script so you won't forget to assign it in the inspector. Hope this helps!
Upvotes: 2
Reputation: 40
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.
Upvotes: 0