简体   繁体   English

如何让Unity 3D中的对象保留在场景中并且不会重新创建

[英]How to have an object in Unity 3D that stays in scenes and does not recreate

I'm trying to find a good way to play background music in Unity 3D. 我正在努力找到一种在Unity 3D中播放背景音乐的好方法。 I want the music to keep playing consistently through scene loads. 我希望音乐能够通过场景加载持续播放。 Don't Destroy on load is fine and works, but every time I load the same scene, it makes another music game object because the scene itself has the game object in it. 不要在加载时销毁很好并且有效,但每次加载相同的场景时,它都会制作另一个音乐游戏对象,因为场景本身中有游戏对象。 How can I solve my problem? 我怎样才能解决我的问题? I am a “beginner” (kind of), so I would like code I can understand. 我是一个“初学者”(有点),所以我想要我能理解的代码。

I'd hands down recommend starting with an Asset like 'EazySoundManagerDemo'. 我建议先从像'EazySoundManagerDemo'这样的资产开始。 It needs a little refactoring and refinement (ie it uses 3 arrays of audios with 3 sets of accessibility functions instead of one set with an AudioPurpose enum to increase code-reuse). 它需要一些重构和细化(即它使用3个音频阵列和3组可访问性函数,而不是一个带有AudioPurpose枚举的集合来增加代码重用)。

It does however solve the basic problem you have and is a good intro to using an audio manager / layer instead of simply playing audio directly from your GameObjects. 然而,它确实解决了您所遇到的基本问题,并且是使用音频管理器/层而不是直接从您的GameObjects直接播放音频的好介绍。 Give that a shot, learn from it and then adapt it or create your own audio management layer. 给它一个镜头,从中学习,然后调整它或创建自己的音频管理层。

Good Luck! 祝好运!

I recommend creating an audioSource object, then creating an script for this object and on the awake function do this: 我建议创建一个audioSource对象,然后为该对象创建一个脚本,并在唤醒函数上执行以下操作:

void Awake() {
    DontDestroyOnLoad(this.gameObject);
}

This will make the background music to keep playing between scenes. 这将使背景音乐在场景之间继续播放。 For more information you could use Unity's documentation about this function . 有关更多信息,您可以使用Unity有关此功能的文档。

With help from a question on the unity forum, I think I have solved my problem. 在团结论坛上的一个问题的帮助下,我想我已经解决了我的问题。 The link to the question is here... 这个问题的链接在这里......

https://answers.unity.com/questions/982403/how-to-not-duplicate-game-objects-on-dontdestroyon.html https://answers.unity.com/questions/982403/how-to-not-duplicate-game-objects-on-dontdestroyon.html

The Best Answer is the one I'm using. 最佳答案就是我正在使用的答案。

The code is this... 代码就是这个......

private static Player playerInstance;

void Awake(){
    DontDestroyOnLoad(this);

    if (playerInstance == null) {
        playerInstance = this;
    } else {
        Destroy(gameObject); // Used Destroy instead of DestroyObject
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM