4

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);
}
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
Anton nelson
  • 333
  • 3
  • 8
  • 18

6 Answers6

4

Just call destroy on it directly:

Destroy(mManager);

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

Almo
  • 15,538
  • 13
  • 67
  • 95
  • Thanks! Where would I put Destroy(mManager);? I tried putting it in my playercontroller.cs didn't do anything. And when I put it into another .js script it said "Unknown Identifier". Any ideas? :/ – Anton nelson Sep 06 '15 at 17:52
  • You need to keep a reference to mManager somewhere that a script can access it when you need to destroy it. I don't know how your project and code are structured, so there's no way for me to know where you need to put this or exactly how to set it up. – Almo Sep 06 '15 at 18:16
1

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"));
}
Anton nelson
  • 333
  • 3
  • 8
  • 18
0

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.

Akash Agarwal
  • 2,326
  • 1
  • 27
  • 57
0

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.

Saad Anees
  • 1,255
  • 1
  • 15
  • 32
0

Maybe it's a little bit late but I use this script and it's works great:

GameObject player = GameObject.FindGameObjectWithTag("Player");
if(player)
 Destroy(player);
0

To achieve this, simply put Destroy(gameObject) in the Update method.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Kadir
  • 21
  • 4
  • This answer is exactly the same as [more well recieved answers](https://stackoverflow.com/a/32425885/14267427). Therefore it should be deleted. – Tyler2P Jul 11 '21 at 09:45