- Home /
How to add field in inspector to change audio on delay
Hi,
I have the following script for playing audio after a certain amount of time has elapsed. Instead of defining the length of time in the script itself, I'd like to add a serialized field so that I can use the script on different game objects and manipulate the time elapsed before playing audio in the Inspector. New to coding. Thanks.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class StartAudioOnDelay : MonoBehaviour {
AudioSource myAudio;
// Use this for initialization
void Start () {
myAudio = GetComponent<AudioSource>();
myAudio.PlayDelayed(3.0f);
}
// Update is called once per frame
void Update () {
}
}
Answer by mlnczk · Nov 20, 2018 at 01:03 PM
[Range(0,10)] // will create editable slider in inspector from values 0 to 10
public float audioLenght;
void Start(){
myAudio = GetComponent<AudioSource>();
myAudio.PlayDelayed(audioLenght);
}
Thank you so much @mlnczk!
Now that I think about it, this is a really annoying way to go about this. I am basically using this to manage 2-3 different pieces of audio within a scene, setting the 2nd and 3rd pieces of audio to deay its start so that it will play after each one finishes.
Using code, is there a way to detect when one audio is finished, and when that audio is finished, to have the 2nd audio play right after, and then a 3rd and so on? $$anonymous$$aybe this will incur less perforamnce costs in Unity(?)
Hmmm maybe try using these AudioSource methods. https://docs.unity3d.com/ScriptReference/AudioSource.SetScheduledStartTime.html https://docs.unity3d.com/ScriptReference/AudioSource.SetScheduledEndTime.html Never used that but I recommend checking always Unity's documentation its pretty good and if you want to do something with e.g AudioSource you can easily check all available methods and examples and see if there is a solution for your problem. Cheers!