How do I play a sound effect that is in an array in a another script?

I have created a SFXManager that holds my sound effects in sfxTracks array. I want to call them from other scripts. I have been searching for days and tried many solutions but to no avail. Here is what seems to be the common solution but it doesn’t work.


public AudioSource sfxTracks;

Calling script

public AudioSource audioSource;

audiosource.clip = sfxMan.sfxTracks [5];
audiosource.Play ();

I always try to solve most problems myself but I can’t seem to find any answers for this one. Thanks

It looks like the problem, based on the code you posted, is that your sfxTracks are type AudioSource rather than type AudioClip. You can either change the type, or say:

audiosource.clip = sfxMan.sfxTracks[5].clip;

I don’t think you’re calling these things correctly. It looks like you already have a reference to your SFXManager instance, so why not just play it from there? This syntax:

audiosource.clip = sfxMan.sfxTracks [5]; audiosource.Play ();

Is incorrect, as AudioSource.Play() doesn’t return anything. Have you tried just assigning it?

audiosource.clip = sfxMan.sfxTracks [5]; audiosource.clip;

Then you should be able to just call:


Thanks everyone for your answers but nothing works. I am missing something.
Vicarian, Yes the AudioSource array is public and i populated it in the inspector. The error I am getting is:

NullReferenceException: Object reference not set to an instance of an object
SceneSwitch+c__Iterator0.MoveNext () (at Assets/Scripts/SceneSwitch.cs:41)

TreyH, I tried yours also but no luck.