我正在使用 SceneManager.LoadSceneAsync
预加载一个新场景来创建动画退出效果,但这给了我错误:
There are 2 audio listeners in the scene. Please ensure there is always exactly one audio listener in the scene.
如何确保我的场景中只有一个音频监听器?
// Public function to change Scene
public void GoToScene(string goToScene)
{
// Starts exit animation and changes scene
CanvasAnimation.SetBool("hide", true);
StartCoroutine(ChangeScene(ExitTime, goToScene));
}
IEnumerator ChangeScene(float time, string goToScene)
{
//Set the current Scene to be able to unload it later
Scene currentScene = SceneManager.GetActiveScene();
// The Application loads the Scene in the background at the same time as the current Scene.
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(goToScene, LoadSceneMode.Additive);
asyncLoad.allowSceneActivation = false;
yield return new WaitForSeconds(time);
asyncLoad.allowSceneActivation = true;
//Wait until the last operation fully loads to return anything
while (!asyncLoad.isDone)
{
yield return null;
}
//Move the GameObject (you attach this in the Inspector) to the newly loaded Scene
SceneManager.MoveGameObjectToScene(ObjToSave, SceneManager.GetSceneByName(goToScene));
//Unload the previous Scene
SceneManager.UnloadSceneAsync(currentScene);
}
谢谢你的帮助
最佳答案
您可以通过检查所有摄像头来确保您拥有一个 AudioListener
。它们通常会自动附加到新创建的相机上。检查每个摄像头并将其移除。您只需要将一个 AudioListener
连接到您的主摄像头。
您也可以通过代码执行此操作:
使用 FindObjectsOfType
在场景中查找 AudioListener
的所有实例,如果它们未附加到 MainCamera,则将其删除。您可以通过检查其 tag
名称(默认情况下应为“MainCamera”)来了解 AudioListener
是否已连接到主摄像头。
AudioListener[] aL = FindObjectsOfType<AudioListener>();
for (int i = 0; i < aL.Length; i++)
{
//Destroy if AudioListener is not on the MainCamera
if (!aL[i].CompareTag("MainCamera"))
{
DestroyImmediate(aL[i]);
}
}
有时,您可能有多个带有“MainCamera”标签的相机。如果是这种情况,请保留 FindObjectsOfType
返回的第一个 AudioListener
,但销毁数组中的 AudioListener
。你留下一个,因为它需要在场景中播放声音。
AudioListener[] aL = FindObjectsOfType<AudioListener>();
for (int i = 0; i < aL.Length; i++)
{
//Ignore the first AudioListener in the array
if (i == 0)
continue;
//Destroy
DestroyImmediate(aL[i]);
}
请注意,Destroy
函数也应该没问题。我选择了 DestroyImmediate
来立即删除它,而不是在另一个框架中执行。
关于c# - 加载场景时删除额外的音频监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49890587/