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

前提是你 提交于 2019-12-05 20:13:51

I'd hands down recommend starting with an Asset like '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).

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. 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:

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.

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

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
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!