Reputation: 163
I am trying to play an audio clip, too big to use PlayClipAtPoint() and I will need to stop it later.
public class GridPower: MonoBehaviour {
private AudioSource audiosource;
public AudioClip poweroff;
int k;
void Start ()
{
audiosource= GetComponent<AudioSource>();
k = 1;
}
void Update ()
{
if (PlayLevel1.percentageLoadProductionint < 100 && StateManager.activeState is PlayState && Time.timeSinceLevelLoad > 1 && k== 1)
{
audiosource.clip = poweroff;
audiosource.Play ();
k = 2;
}
}
}
I followed some documentation but unity tells me that there is no AudioSource attached to the game object where the script is located.
Can you help?
Upvotes: 1
Views: 156
Reputation: 12621
this is totally wrong. delete any and all mentions of "AudioClip" - you never, ever use it in code.
(1) make an empty game object (call it say "test"). (2) put an AudioSource on it - whatever audio you like. (3) in your script, have a public inspector variable to pick up the AudioSource on test. (4) just Play that audio source. honestly it's just that simple. say you have maybe 20 different songs. just have 20 different game objects like "test". It is really just that simple.
Say you have 500 sound effects in a project. you simply have 500 game objects (like "test" in the example) each one with the different sound on it.
(of course, just have one empty game object, to sit them all "under", to keep it tidy.)
Note - an awesome feature in Unity is, select and drag say 100 sound effects (or whatever audio) from assets in to the scene: note that it "knows" to put each one on a game object for you. this was a huge addition in Unity5.
it's just that simple.
Upvotes: 2