Can't get Sound working but music is fine

So I have the background music playing and hooray for that. However I can’t get the one-shot sound effects to work as they are supposed to.

    public AudioClip caughtGood;
    public AudioClip caughtGold;
    public AudioClip caughtBad;
    public AudioClip combo_increased;
    
    ...
    void Start ()
    {
    	... // previous code	
    	if((caughtBad != null || caughtGold != null || caughtGood != null || combo_increased != null) &&
    		audio == null) {
    		AudioSource source = gameObject.AddComponent<AudioSource>();
    		source.playOnAwake = false;
    	}
    }

   void PlaySound(AudioClip source) {
    	if(audio && source) {
    		audio.PlayOneShot(source);
    	}
    }

Then I am calling for example:

private void incrementCombo () {
	if (comboCount < 2) {
		comboCount++;
	} else {
		...
		PlaySound(combo_increased);
		...
	}
}

Can someone please help me out. It is really weird why it won;t work.

I f you don't have any luck, suggest it to Unity Support on the forums. Or maybe just ask them, they should know, they wrote the bloody thing :P

1 Answer

1

There are a couple of things about your PlaySound method.

  1. You’re passing a source, so you probably don’t need to check that source is not null.
  2. PlayOneShot takes an AudioClip as an argument, not an AudioSource. (ref)

What you probably want to do in PlaySound is this:

void PlaySound(AudioSource source)
{
    source.Play();
}

You may also want to set the AudioSource.loop variable to control the behavior of playing.

But then the question is...why even have a method that does that? Perhaps you should just call it in your original 'else' statement. :)