Hi, I want to have 4different bgm for 4 stages (in one scene).
So, for example, If my character steps on the first stage, then first bgm will be played,
and if my character moves to the next stage, bgm changes to the other one.
Sth like that. I guess it will be easier to use the tag for this?
I’m really struggling with this right now… I’m design student, so this coding stuff is totally new for me.
It sounds like you need a simple AudioManager script where you create 4 audioclip variables for each soundtrack and attach that to a new gameobject where you can also add an audiosource.
using UnityEngine;
public class AudioManager : MonoBehaviour
{
public AudioSource musicSource; // Reference to the AudioSource component for music
public AudioClip[] musicTracks; // Array of music tracks to choose from
private int currentTrackIndex = 0;
void Start()
{
// Initialize the AudioManager with the first music track
PlayMusic(0);
}
public void PlayMusic(int trackIndex)
{
// Check if the trackIndex is within the bounds of the musicTracks array
if (trackIndex >= 0 && trackIndex < musicTracks.Length)
{
// Set the currentTrackIndex
currentTrackIndex = trackIndex;
// Stop the current music and change the clip
musicSource.Stop();
musicSource.clip = musicTracks[trackIndex];
// Play the new music track
musicSource.Play();
}
}
public void NextTrack()
{
// Play the next music track in the array
currentTrackIndex = (currentTrackIndex + 1) % musicTracks.Length;
PlayMusic(currentTrackIndex);
}
public void PreviousTrack()
{
// Play the previous music track in the array
currentTrackIndex = (currentTrackIndex - 1 + musicTracks.Length) % musicTracks.Length;
PlayMusic(currentTrackIndex);
}
}
CodeMonkey has a great tutorial on how to create a simple audio manager you can also check out (but there are plenty of other great tutorials on that from the community):