- Home /
Is there a more efficient way to trigger an audio source from an array to play than using a timer?
I don't quite remember exactly which tutorial I was watching but the instructor mentioned that he uses an array to store audio clips in and be able to adjust settings for all in inspector through an audio manager. I followed this example and seems to be working well except for a particular situation I have run into. Because of the way the array is set up, I seem to have trouble identifying whether or not a certain clip is playing. I have theme music playing in the background. One clip contains the intro as well as the main melody and the second only has the main melody which should pick up where the first one leaves off and then just continue to loop for the remainder of the game. I'm currently using a timer method to count the time until the first clip should stop playing then play the second. I can edit the transition to be fairly smooth in editor but once i build, the timing varies depending on what device is being used. Is there a more effective method to use?
This is the script my AudioManager is currently using:
using UnityEngine.Audio;
using UnityEngine;
using System;
public class AudioManager : MonoBehaviour
{
public float timer;
public float partyTime;
public Sound[] sounds;
public bool theme2IsPlaying = false;
// Start is called before the first frame update
void Awake()
{
foreach (Sound s in sounds)
{
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
s.source.volume = s.volume;
s.source.pitch = s.pitch;
s.source.loop = s.loop;
}
}
void Start()
{
Play("Theme");
timer = 0f;
}
public void Update()
{
timer += Time.unscaledDeltaTime;
if (timer >= partyTime)
{
if (theme2IsPlaying == false)
{
Play("Theme 2");
theme2IsPlaying = true;
}
else
{
return;
}
}
}
public void Play (string name)
{
Sound s = Array.Find(sounds, sound => sound.name == name);
if (s == null)
{
Debug.LogWarning("Sound" + name + "not found!");
return;
}
s.source.Play();
}
}
Your answer
