问题
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