Unity: Audio Manager for different scene music - c#

I want to have a background music to play seamlessly from “Scene1” to “Scene2” but I want the music to change if I load “Scene3” or “Scene4” (which should have the same behavior). How can I achieve this?

First your music playing gameobject should be using DontDestroyOnLoad functionality, so the music player does not destroy when the scene changes. If you're not using it, read about it here : https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
After that, the music player could use SceneManager to decide if it should switch the track or not on scene change.

There is a solution for this in Unity forums SOLUTION
using UnityEngine;
public class MusicClass : MonoBehaviour
{
private AudioSource _audioSource;
private void Awake()
{
DontDestroyOnLoad(transform.gameObject);
_audioSource = GetComponent<AudioSource>();
}
public void PlayMusic()
{
if (_audioSource.isPlaying) return;
_audioSource.Play();
}
public void StopMusic()
{
_audioSource.Stop();
}
}
If you want it to change after just change the audio clip like HERE
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class ExampleClass : MonoBehaviour
{
public AudioClip otherClip;
IEnumerator Start()
{
AudioSource audio = GetComponent<AudioSource>();
audio.Play();
yield return new WaitForSeconds(audio.clip.length);
audio.clip = otherClip;
audio.Play();
}
}

Related

Doors in Unity Mp Networking

I’ve been struggling for the past 8 hours to make my door work in multiplayer. With the code I have, i can use the door in singleplayer and in mp only the host can trigger the door animation and walk through it, other players can neither walk through it or even open it. I figured out i have to connect the door to the network.
I’m using mirror into my project and I’ve tried a lot of fixes but noone seem to work. I’ve tried usinc RPC’s, commands, authority, but can’t get it to work even using chat gpt so i tought to try asking a real human. I ve pasted my working code for single player down below, if anyone has any idea, everything is greatly appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoorScript : MonoBehaviour
{
[Header("MaxDistance you can open or close the door.")]
public float MaxDistance = 5;
public AudioClip openSound;
public AudioClip closeSound;
private bool opened = false;
private Animator anim;
private Camera playerCamera;
private AudioSource audioSource;
void Start()
{
// Find the player object by tag and get the camera component from it
GameObject player = GameObject.FindGameObjectWithTag("Bosu");
if (player != null)
{
playerCamera = player.GetComponentInChildren<Camera>();
}
// Get the AudioSource component from the same game object as the DoorScript
audioSource = GetComponent<AudioSource>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Pressed();
}
}
void Pressed()
{
RaycastHit doorhit;
if (Physics.Raycast(playerCamera.transform.position, playerCamera.transform.forward, out doorhit, MaxDistance))
{
if (doorhit.transform.tag == "Door")
{
anim = doorhit.transform.GetComponentInParent<Animator>();
opened = !opened;
anim.SetBool("Opened", opened);
// Play the open or close sound based on the current state of the door
if (opened)
{
audioSource.PlayOneShot(openSound);
}
else
{
Invoke("PlayCloseSound", 0.6f);
}
}
}
}
void PlayCloseSound()
{
audioSource.PlayOneShot(closeSound);
}
}

How to get sound woking in unity

I hope you are having a good day. Today on 30/08/2022 I sat down to work on my game in unity 2021.3.6f1 on my ubuntu 20.04 computer and all the audio was on playing I made new sound tracks but, the sound tracks still didn't play at all. If anyone knows how to fix it plz help.
The sound manager code I use is:
using System;
using UnityEngine;
using UnityEngine.Audio;
public class AudioManager : MonoBehaviour
{
public Sound[] sounds;
private void Awake() {
foreach (Sound s in sounds) {
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
s.source.volume = s.volume;
s.source.pitch = s.pitch;
s.source.loop = s.loop;
}
}
public void Play(string name) {
Sound soundToPlay = Array.Find(sounds, sound => sound.name == name);
soundToPlay.source.Play();
}
}
The "Sound" class code:
using System;
using UnityEngine;
using UnityEngine.Audio;
[System.Serializable]
public class Sound {
public string name;
public AudioClip clip;
[Range(0f, 1f)]
public float volume = 1f;
[Range(1f, 3f)]
public float pitch = 1f;
[HideInInspector]
public AudioSource source;
public bool loop = false;
}
Make sure that the Audio Icon is not clicked. And make sure that this is not getting set to off when the game is running. If all the code is working, I would guess its this.

continuing same Audio while changing scene - Unity

So I wanted to continue the same music from the same time while changing from the main menu to a new scene. so I did this:
using UnityEngine;
public class AudioManager : MonoBehaviour
{
public AudioSource bgm;
void Update()
{
DontDestroyOnLoad(bgm);
}
}
this works fine. but when I come back to the main menu the same music starts playing twice at the same time. So what can I do so that this doesn't happen?
Remove the Update function including the "DontDestroyOnLoad(bgm)" Line
Remove the variable named bgm
Create a static instance variable of the class in the class itself and use it to check whether you should destroy it or not. Example:
private static AudioManager audioManager;
private void Awake() {
DontDestroyOnLoad (gameObject);
if (audioManager == null) {
audioManager = this;
} else {
Destroy(gameObject);
}
}

Unity Unexpected Sound Behavior

Im taking a Unity C# course on Udemy, and we got to an challenge and i came up with a very simple "game". My problem is i can't figure out why no sound is playing? I looked at the instructors code and is the same as my (or did i just miss something?)
When i press on space the rocket starts flying (this works) and should play sound (it doesnt). Yes i got a SoundListener attached to the main camera.
Can somebody help and explain me where i missed something?
Here is my code that i wrote:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rocket : MonoBehaviour
{
Rigidbody rigidBody;
AudioSource audioSource;
// Use this for initialization
void Start()
{
rigidBody = GetComponent<Rigidbody>();
audioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
ProcessInput();
}
private void ProcessInput()
{
if (Input.GetKey(KeyCode.Space)) // can thrust while rotating
{
rigidBody.AddRelativeForce(Vector3.up);
if (!audioSource.isPlaying) // so it doesn't layer
{
audioSource.Play();
}
}
else
{
audioSource.Stop();
}
if (Input.GetKey(KeyCode.A))
{
transform.Rotate(Vector3.forward);
}
else if (Input.GetKey(KeyCode.D))
{
transform.Rotate(-Vector3.forward);
}
}
}
Solved it after after declaring the audioSource to public

Audio Source Not Playing Unity3d?

I am trying to play an AudioSource when the trigger is entered by the player but for some reason nothing is working.
I have an Audio Source on the coin that the player will pick up and a sound attached to that audio source.
using UnityEngine;
using System.Collections;
public class DingSoundPlay : MonoBehaviour {
public AudioSource DingAudioSource;
void OnTriggerEnter (Collider other)
{
if (other.tag == "Player")
{
DingAudioSource.Play();
Debug.Log ("Sound Played");
}
}
}
What am I doing wrong??
It might be better for a Coin sound to use the PlayOneShot() method for this, this needs an AudioClip though:
public AudioClip audioClip
DingAudioSource.PlayOneShot(audioClip);

Categories

Resources