Object instantiation Logic Javascript.

Holla, i try to instantiate an object to the scene, which is the music background… and i want this music to keep playing on the next scene

so first thing i have create the prefab.

and this is my script up till now…

#pragma strict
var bgSound : GameObject;
bgSound = GameObject.Find("bg_sound");

function Awake() {
	
	if(GameObject.Find("bg_sound")==null){
		Instantiate(bgSound,Vector3(0,0,0), Quaternion.identity);
		DontDestroyOnLoad(bgSound);
	}
	else if(GameObject.Find("bg_sound(clone)")!=null){
		//dont instantate new object..
		
	}
}

but i dont know how to not instantiate new object, i know my logic seems off… but i really think hard (lol) how to do this… could someone please fix/give me some advice?

Your main problem is that you put bgSound = GameObject.Find("bg_sound"); outside of a function, where it won’t work.

You actually don’t need to Instantiate it at all, you can just put the AudioSource on your main control script and then in Awake put DontDestroyOnLoad (this.gameObject). That will make your controller object persist, along with its music, from one scene to the next.