Most of the functions in unity can be implemented through drag and drop, but in order to facilitate the introduction, code is used here.
There are three main elements for playing music in Unity:
1. audiosource: controls the subject of music playback.
2. audioclip: The music to be played.
3. audiolistener: add this control to hear the effect of playing music.
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: add an audiosource to the gameobject. The added function returns the added control and assigns the returned control to m_audiosource.
Line 2 code: Same
Line 3: Load music from resource/music/Haha. Haha is the name of the music.
Line 4 Code: play music.