0
\$\begingroup\$

I have two sound clips that I am feeding to an audioSource via script, it seems to be working as I can see the audio clips populating the audioSource component. But the problem is that I dont hear anything.

How ever if I remove the script and manually select the audioclip in source then I can hear both clips clearly. Why is this not working when done through script:

Here is my small script, its choosing two sounds based on the navMeshAgent status.

public class KnightAudio : MonoBehaviour {

    //private Animator anim;
    private NavMeshAgent agent;

    private AudioSource knightAudio;
    public AudioClip crying; //set this in ispector with audiofile
    public AudioClip scream; //set this in ispector with audiofile

    // Use this for initialization
    void Start () {
        knightAudio = GetComponent<AudioSource>();
        agent = GetComponent<NavMeshAgent>();
        //anim = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update () {
        if (!agent.isStopped)
        {
            knightAudio.clip = scream;
            knightAudio.Play();
        }
        else
        {
            knightAudio.clip = crying;
            knightAudio.Play();
        }

    }
} 

Here is the audio source, as can be seen it is populating the crying clip in there as expected when the agent is stopped and it will change this to scream when agent starts moving. But in game I cannot hear any of these.

enter image description here

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

Could be that since you're having the audio play every frame that it's constantly restarting the clip making it sound as though nothing is being played.

\$\endgroup\$
0
\$\begingroup\$

The reason it wasnt working was that I was playing it in update without any checks and it was trying to play every frame. Thats why I couldnt hear anything.

Here is the fixed code:

void Update () {
        if (!agent.isStopped)
        {
            if(knightAudio.clip != scream)
            {
                knightAudio.clip = scream;
                knightAudio.Play();
            }
            else if (knightAudio.clip == scream && !knightAudio.isPlaying)
                knightAudio.Play();

        }
        else
        {
            if (knightAudio.clip != crying)
            {
                knightAudio.clip = crying;
                knightAudio.Play();
            }
            else if (knightAudio.clip == crying && !knightAudio.isPlaying)
                knightAudio.Play();
        }
    }
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .