How to destroy a game object marked “DontDestroyOnLoad” when a new scene loads?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 03:48:15

问题


So I created a music player to play music through all my menu and story scenes without interrupting, but then in my game scene I want to delete that music. How can destroy the playing music when my game scene loads?

Here is my music script:

#pragma strict

var offsetY : float = 40;
var sizeX : float = 100;
var sizeY : float = 40;

var musicPrefab : Transform;

function Start () {

if (!GameObject.FindGameObjectWithTag("MM")) {
    var mManager = Instantiate (musicPrefab, transform.position, Quaternion.identity);
    mManager.name = musicPrefab.name;
    DontDestroyOnLoad (mManager);
}
}

回答1:


Just call destroy on it directly:

Destroy(mManager);

DontDestroyOnLoad only protects the object from being destroyed when loading a new scene.




回答2:


I created a script called Destroyer.js and attached it to the camera in the scene where I didn't want music. Then in that script I added this code, and it doesn't play anymore.

function Start() {

Destroy(gameObject.Find("_MMusic"));
}



回答3:


You can destroy the object by calling Destroy(objectname) directy like mentioned above by Almo. You could place it in the same function call which is responsible for the change to the scene where you don't want the music to be playing.




回答4:


I had the same issue so I tried Destroy(gameObject); as mentioned in answers above but It didn't work for me.

So I tried SceneManager.LoadScene("OtherSceneName", LoadSceneMode.Additive); and it worked for me. Read official docs here.



来源:https://stackoverflow.com/questions/32425830/how-to-destroy-a-game-object-marked-dontdestroyonload-when-a-new-scene-loads

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