I want to assign gameobjects with audio source which is in game scene to a slider which adjusts volume and its in mainmenu scene.How to do it ?
You can only load 1 scene at a time, but you can carry game objects from 1 scene into the next (i.e. when you load the second scene, you can instruct your game objects, through code, to remain loaded in the scene…otherwise, they will be unloaded when switching scenes). So you have 2 choices. Load the menu scene first and add a call to DontDestroyOnLoad() to the Awake() or Start() method in a script on your UI game object. Or option 2) if you plan to only ever have 2 scenes, move the menu components into the second scene where they are directly usable.
With option 1, since the game objects for your UI aren’t readily available in your 2nd scene, you won’t be able to use drag & drop to reference public members between UI and game objects (i.e. your sound source and sound listener objects). So you’ll need to tag the sound objects you want to control and search for them from the UI slider when the slider moves, in order to update the volume. Optionally, you could create a Singleton script and assign it to the sound objects, and it could expose a public method to adjust the sound using the static instance, like so:
static SoundScript _instance;
public Awake() {
_instance = this;
}
public static void AdjustVolume(float level) {
_instance.GetComponent<AudioSource>().volume = level;
}
Using DontDestroyOnLoad will keep the object between scenes.
Here is an example I use for Photon. It detect if it’s already there or not, and if it’s not, it instantiates a game object. Where on the gameObject it instantiates, it has the DontDestroyOnLoad.
using UnityEngine;
using System.Collections;
public class MakePhotonServer : MonoBehaviour
{
public GameObject ServerPrefab;
public GameObject AnnouncementPrefab;
public bool SpawnAnnouncement = false;
void Awake()
{
if (GameObject.Find("Photon Server") == null)
{
Debug.Log("Creating Photon Server!");
GameObject i = (GameObject)Instantiate(ServerPrefab);
i.name = "Photon Server";
}
if (SpawnAnnouncement)
{
if (GameObject.Find("lbl_Announcement") == null)
{
Debug.Log("Creating Announcement Label.");
GameObject b = (GameObject)Instantiate(AnnouncementPrefab);
b.name = "lbl_Announcement";
//b.transform.parent = GameObject.Find("UI_Root").transform;
}
}
}
}
I hope that helps.