Unity Scripting Question

Hi

I am currently trying to do the following in a simple Unity 3D scene:

  • Load the scene
  • After 5 seconds have passed, play an audio clip in its entirety
  • Never allow the clip to play again

float levelStartTime;
float audio1StartTime;
bool audio1Locked;
public AudioClip audio1;
public AudioSource audioSource1;

void Start () {
audio1Locked = false;
audio1StartTime = 5.0f;
levelStartTime = Time.time;
}

void Update () {
if (havePassed5Seconds())
{
if (!audio1Locked)
{
playAudioClip(audioSource1);
}
}
}

void playAudioClip(AudioSource source)
{
source.clip = audio1;
source.PlayOneShot(audio1, 1.0f);
audio1Locked = true;
}

bool havePassed5Seconds()
{
if (Time.time - levelStartTime > audio1StartTime)
{
return true;
}
else
{
return false;
}
}

The problem I have is that my clip is around 16 seconds long yet Unity stops playing the clip after 2-3 seconds.
If I don’t set audio1Locked = false then the clip plays infinitely.

I feel this may be a simple issue but I can’t seem to figure out what is happening.

Any help would be appreciated.

Much simpler for this might be:

void Awake(){
   audioSource1.clip = audio1;
   Invoke("PlayAudioClip", 5f);
   }
void PlayAudioClip() {
   audioSource1.Play();
   }

If you need to change clips or anything else, please elaborate in your question.
This just seems simpler for what you described in your OP.

1 Like

Thanks for the quick reply. Much more elegant solution right there too. Cheers

You’re welcome.