The American Fox
The American Fox

Reputation: 155

Audio not playing in Unity

I am trying to program a script that when you hit an enemy it plays a sound, problem is I can't get it to play the sound it sees the audio source but my script won't pass the clip to it.

Here is the code I currently have:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;

public class makeanoise : MonoBehaviour
{
    public AudioClip hurtSound;
    public AudioSource soundSource;

    private void Update()
    {

        if (!soundSource.isPlaying)
        {
            soundSource.clip = hurtSound;
            soundSource.Play();
        }
    }
}

how do you get the audio source to play the sound? because not even my team mates know to do it

Upvotes: 13

Views: 47176

Answers (7)

Joe M
Joe M

Reputation: 1

Landed on this old question as I had the same issue, but solutions here didn't fix - I suspect my problem was likely too obvious to have been included on answers given so far, but sometimes there's no such thing as too obvious...

There is a global project audio level, which was set to 0 (I presume I inadvertently changed it myself, as it seems an odd default). On v. 2021.3, can change via Edit > Project Settings > Audio, and there's a Global Volume setting at the top.

Upvotes: 0

ow3n
ow3n

Reputation: 6587

The checklist provided by @Programmer helped me to remove other possibilities and find yet another potential problem to consider...

If your audio works fine in the Unity editor but not in the build, it could be that you are using OnValidate() to store the reference to your AudioSource component in a private field. Specifically, Unity does not serialize values in private fields unless explicitly instructed

How to confirm / fix it:

  1. Enable "Development Build" so the build will report issues
  2. The build log shows NullReferenceException: Object reference not set to an instance of an object when you try to play or otherwise access the AudioSource.
  3. Add [SerializeField] to any private vars set using OnValidate() to be sure the reference is serialized:
[SerializeField] private AudioSource audioSource;
void OnValidate()
{
    audioSource = GetComponent<AudioSource>();
}

build settings

Upvotes: 0

hutch90
hutch90

Reputation: 351

I solved this by playing AudioSource.clip at the position of the main camera. Passing in a Vector3 with x, y, and z all equal to 0 played the sound, but it was quieter. I never got AudioSource.Play() to work.

AudioSource.PlayClipAtPoint(audioSource.clip, mainCamera.transform.position);

Upvotes: 0

Corey Rodgers
Corey Rodgers

Reputation: 41

Just to help anyone else out, the pitch settings like ash a mentioned actually can cause some strange bugs, the pitch of my audio source was set to -1 as I have a mechanic where points increase the sfx pitch by clicking on things in succession. using AudioSource.PlayClip at point allowed the sound to play but I then removed AudioSource.PlayClipAtPoint to use the cached AudioSource, made sure the pitch initialized at 1f when I wanted the GameOver sounds to play and all worked as expected.

Upvotes: 0

ash a
ash a

Reputation: 11

One more thing that can cause that it the Pitch settings - i had mine on 0 - i could see the audio playing in the mixer - but no sound would be heard - moved pitch back to 1 - and everything worked well.

Upvotes: 0

Programmer
Programmer

Reputation: 125245

I am trying to program a script that when you hit an enemy it plays a sound

Use collision detection + collider instead of the Update function to detect the hit then play audio:

void OnCollisionEnter(Collision collision)
{
    soundSource.Play();
}

If 2D game, use OnCollisionEnter2D instead.

I can't get it to play the sound it sees the audio source but my script won't pass the clip to it.

There are just many reasons why Audio many not play in Unity. Your sound won't play not because you put it in the Update function.The reason it's not the Update function like some mentioned is because you protected it with if (!soundSource.isPlaying) so it will only play again only when the first one is doe playing.

Reasons why audio won't play in Unity: (From likely to unlikely)

1.The AudioClip is not assigned.

This is your AudioClip

public AudioClip hurtSound;

If hurtSound not assigned or initialized in the Editor or via code, Unity won't throw any error. It simply won't play.

Simply drag the audio to your hurtSound slot and you should hear the sound. Sometimes, the audio reference is lost so simply repeat this step again to recreate the reference.

enter image description here


2.Editor is muted. If the Editor is muted no sound will be coming out of it but the build should have a sound. Check and disable the mute on the Editor.

enter image description here


3.Playing the sound every frame. This mistake is not uncommon and it causes the AudioSource not have time to play the audio over and over again.

Example of this mistake:

private void Update()
{
    soundSource.Play();
}

Possible fix:

Check the Audio is playing first before playing it.(Did this in the code from this question which is correct!)

private void Update()
{

    if (!soundSource.isPlaying)
    {
        soundSource.Play();
    }
}

4.The GameObject the AudioSource is attached to has been destroyed. This is also common. If the GameObject the AudioSource has been attached to is destroyed, the Audio would not play.

The fix is to attach the AudioSource to GameObject that doesn't destroy. An empty GameObject is fine.

Or you can play the Audio, wait for it to finish playing then destroy it:

IEnumerator playAudio()
{
    //Play Audio
    soundSource.Play();

    //Wait until it's done playing
    while (soundSource.isPlaying)
        yield return null;

    //Now, destroy it
    Destroy(gameObject);
}

5.The GameObject the AudioSource is attached to has been deactivated.

If the GameObject that has the Audiosource is deactivated, the audio would also stop. Don't deactivate the AudioSource GameObject. See #4 for possible workarounds.

enter image description here


6.The code is not even executing.

You must make sure that the Play code is even executing. A simple Debug.Log function call is enough to determine this.

private void Update()
{

    if (!soundSource.isPlaying)
    {
        soundSource.clip = hurtSound;
        soundSource.Play();
        Debug.Log("Played");
    }
}

enter image description here

If you can't see that log in the Console tab then the code is not executing.

A.Script is not attached to a GameObject. Attach it to a GameObject:

enter image description here

B.The GameObject the script is attached to is not Active. Activate it from the Editor:

enter image description here

C.The script is not enabled. Enable it:

enter image description here


7.The AudioSource is muted or volume is 0.

enter image description here


8.The AudioListener component is not present. This is very unlikely since it is automatically attached to your camera. Check if it is deleted by mistake then re-attach it to the camera. It must be attached to the camera not to any other object.

enter image description here


9.Bad Audio. Replace with another Audio.

10.Bug. Go to the Help ---> Report a Bug.. menu and file for a bug report.

This is what to do if everything above has failed. This is unlikely the problem but could happen when there is a big OS update.

Upvotes: 23

Chopi
Chopi

Reputation: 1143

You need to have a AudioListener in the scene and also check the 3D sounds settings, the most usual thing is having the AudioListener attached to the main camera.

Check if in the scene is there any AudioListener and the Settings of your AudioSource

Upvotes: 1

Related Questions