c# - 加载场景时删除额外的音频监听器

标签 c# unity3d asynchronous

我正在使用 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/

相关文章:

c# - LINQ 将数组 [x0,y0, ..., xN, yN] 转换为可枚举的 [p0, ..., pN]

c# - 是否可以录制游戏中的声音,将其保存,然后使用C#将其作为常规歌曲在手机上播放?

c# - Unity 在 Start() 函数中查找带有组件的子项失败

android - 文档中的 Unity3d Input.location 在代码中不可用

Javascript - 检查对象属性存在时避免异步竞争条件

asynchronous - 脚本错误(:0) when trying to run async test in mocha-phantomjs

c# - 如何在 UWP 的 NavigationViewMenuItems 中添加自定义图标

c# - 如何引用 NuGet 包的匿名命名空间中的内容?

c# - Ninject 根据顶级项目获得不同实现的最佳实践

c# - 取消不接受 CancellationToken 的异步操作的正确方法是什么?