0
\$\begingroup\$

When I start my game, public AudioSource does not load sound but play a sound. My code does not have any error.

using UnityEngine;
using System.Collections;

public class random: MonoBehaviour {

    public AudioClip[] gravel;

    void Update()
    {
        if (!GetComponent<AudioSource>().isPlaying){
            GetComponent<AudioSource>().PlayOneShot(gravel[Random.Range(0,gravel.Length-1)]);
        }
    }
} 

How can I put my random audio to my audio source. Video for describle my problem: In this video play sound twice (because I run my game twice) In first play I have to attach a file to audio source. I do not know why my audio source is empty and I have to attach a file to it. If I can load sound in my audio source I can fix my problem. I want to play one randomized shot.

\$\endgroup\$
1
  • \$\begingroup\$ What do you mean by first play and second play? \$\endgroup\$ – Hamza Hasan Dec 12 '15 at 10:21
1
\$\begingroup\$

First of all your first sound playing well because you assigned it explicitly and you have mark on check Play On Awake.Uncheck it.

You can do something like,

public AudioClip[] _gravel;
private AudioSource _aSource;

void Start()
{
    // Get attach audio source once.
    _aSource = GetComponent<AudioSource>();

    // Start Coroutine for playing sounds. Call it once
    StartCoroutine("PlaySound");
}

void Update()
{
}

IEnumerator PlaySound()
{
    _aSource.clip = _gravel[Random.Range(0,_gravel.Length)];
    _aSource.Play();
    yield return new WaitForSeconds(_aSource.clip.length);
    StartCoroutine("PlaySound");

}

// ===== OR ===== //

IEnumerator PlaySound()
{
    while(true){
        _aSource.clip = _gravel[Random.Range(0,_gravel.Length)];
        _aSource.Play();
        yield return new WaitForSeconds(_aSource.clip.length);   
    } 
}
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.