Can not get a simple AudioSource to play via script

I’m still pretty new at Unity and I’m getting stuck on simple things, I’m sure I’m missing something obvious here but I don’t know what.

Here’s the situation:

  • I create a GameObject, give it AudioSource Component, and associate an audioclip.
  • If I leave the AudioClip as a 3d sound, and set the AudioSource to Play On Awake, it works fine.
  • If I change this same sound to a 2d sound, leaving Play On Awake on, I hear nothing (this is problem #1)
  • If I turn off Play on Awake, and then try to play the file via script, nothing happens. Specifically, in C#:
print("audio is: " + audio + " clip: " + audio.clip);
audio.Play();

Does nothing at all. The print statement does print what I would expect ( “audio is: AudioTester (UnityEngine.AudioSource) clip: monkeyyes (UnityEngine.AudioClip)” ).

  • The Play() produces no sound regardless of the 3d/2d setting. Sound does not play in Game preview or in standalone PC modes.

So what’s the dumb thing I’m doing wrong here? Any help would be appreciated.

Give this a go.

function Update(){
   
   if(!audio.isPlaying){
      audio.Play();
	  print("audio is: " + audio + " clip: " + audio.clip);
   }
}

Thanks for the suggestion, this also does not play.

Maybe it’s something to do with my sound file?

see if you can play any sound file from any device on your system. Sometimes my sound goes out and its nothing Unity and a simple reboot fixes it.

Strange… My code worked when I tried it.

Does the sound play in Unity’s preview window.
What Tiddles said for checking for .isPlaying should work. In fact since 3.5 you need to do this, as playOnAwake alone no longer plays the sound.