- Home /
Audio Not working
Hi, I'm currently working on a game called Food Fight. I would like a sound to play when your player jumps. I have tried and it didn't work, even after following a bunch of YouTube tutorials. This is my current code
public AudioSource audioSource;
public AudioClip clip;
public float volume = 0.5f;
void Update()
{
if(Input.GetButtonDown("Jump") && extraJumps > 0)
{
audioSource.PlayOneShot(clip, volume);
}
}
Can someone please tell me what I'm doing wrong?
Answer by Psycho8Vegemite · Oct 22, 2020 at 10:43 AM
Have you checked to make sure that you have an AudioListener in the scene? Usually, this is added with the MainCamera so you can check there, otherwise, manually add one in and hit play. If the Unity Console says something like "There can only be one AudioListener in the scene" then remove the one you added.
On top of that, make sure that the AudioSource that you're trying to make play a sound is active. If it isn't active it won't play a sound.
Another thing could be testing if your code is executing or not, try adding the line Debug.Log("I work!");
inside the if
block. If "I work" isn't logged in the console whenever you press the 'Jump' button and the other condition should be met, then your code isn't being executed and may need more iteration.
If it is code related, another way to improve on the code you currently have is by calling a method instead of running this code separately. This would make your code more reliable and cleaner.
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private AudioManager audioManager;
private void Update ()
{
if(Input.GetButtonDown("Jump") && extraJumps > 0)
{
// Do your jumping code here
audioManager.PlayJumpSound();
}
}
}
// Seperate file
public class AudioManager : MonoBehaviour
{
[SerializeField] private AudioSource source;
[SerializeField] private AudioClip clip;
[SerializeField] private float volume = 0.5f;
public void PlayJumpSound ()
{
audioSource.PlayOneShot(clip, volume);
}
}
Your answer
Follow this Question
Related Questions
Accessing low passed filtered audio data 0 Answers
Audio Loops? 1 Answer
audio from mic, db value keeps getting stuck at - infinity ? 0 Answers
Timeline Audio Source problem using Cinemachine 1 Answer
Calling sound once in update 1 Answer