Most of the functions in unity can be implemented by dragging and dropping, but in order to facilitate introductions, they are all implemented in code here.
There are 3 main elements to play music in Unity:
1.AudioSource: Controlling the body of music playback
2.AudioClip: Music that needs to be played
3.AudioListener: Add this control to hear the effect of music playback
The code is as follows:
Audiosource M_audiosource = gameobject.addcomponent<audiosource> (); Audiolistener M_audiolistener = gameobject.addcomponent<audiolistener> (); AudioClip m_audioclips = (audioclip) resources.load<audioclip> ("Music/haha"); M_audiosource.playoneshot (m_ Audioclips);
The first line of code: To add a audiosource to Gameobject, the added function returns the added control and assigns the returned control to M_audiosource.
Second line of code: similarly
The third line of code: loading music from Resource/music/haha, haha is the name of the music.
The four lines of code: play Music.
[Unity-2] Unity plays Music