create audioSource via script?

i tryed this but not work , why

 private AudioSource m_audioSource;            

start()
{
m_audioSource = new AudioSource();
m_audioSource.loop = true;
}

and when it hit the “loop = true;” i get an error
i figure im not creating the AudioSource correctly .
the way im writing the code , it CANNOT be done via the inspector
so it has to be done via compleate script . any ideas how to do this ?

found the problem , it should have been m_audioSource = gameObject.AddComponent(); cause its a Component

–

1 Answer

1

AudioSource audioSource = gameObject.AddComponent();
audioSource.clip = Resources.Load(name) as AudioClip;
audioSource.Play();

You need to have a clip assigned. In this example, I use Resources.Load(), but you could just use an assigned AudioClip or something like that.

Cheers :wink:

to use Resources.Load(name) do you need the prefab in be in a specific folder?

–

Resources.Load loads assets from an existing Resourses folder under your Assets folder. (Assets/Resources) You can still have subfolders like Assets/Resources/Textures Then you will need to do something like this: Resources.Load("Textures/diffuse");

–

perfect answer :) thnx @Tim Michels

–

For those on 2017.1 version this is a solution which works for first line, as per updated API for library function for AddComponent var audioSource : AudioSource = gameObject.AddComponent.<AudioSource>() as AudioSource;

–