- Home /
How to add audio source to gameobject with PlayOnAwake turn on through script?
I have an audio manager script which take in an array of "sounds" (a custom serializable class that has public variables like: AudioClip clip, string name, float pitch,... and bool PlayOnAwake). In the awake function of the manager script for each "sound " i add a audio source and set all of its settings to match the "sound" settings (clip, pitch, ...). It worked fine until i wanted to add the bool PlayOnAwake. For some special audio i want it to play automatically rather then call it manually so i add the PlayOnAwake bool and set the AudioSource to that. But i think because i set it after i add the component to the object so it wouldn't play automately. How to achieve something like this?
Answer by SmartCarrion · Apr 30, 2020 at 04:13 AM
You could instantiate a prefab that already has it set up how you want, or simply call Play() in your script instead of setting PlayOnAwake!
Yeah i've already called play in the awake function if the bool is true.
Your answer
![](https://koobas.hobune.stream/wayback/20220612232853im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Problem with playing sound on Trigger-Enter 2 Answers
How to get decibel's value of game's sound? 0 Answers
Play audio at consistent volume 2 Answers
AudioSource won't play 2 Answers