I have an audio object in a scene with “Play On Awake” and “Loop” enabled. I also have the following script attached to it:
function Awake() {
DontDestroyOnLoad(this);
}
This is basically background music that plays throughout the game (from the Main Menu onwards). Works fine in Unity iPhone 1.7.
I’ve noticed in Unity 3 Beta 7 that if I go from the Main Menu to the “Options” screen (or whatever) then it’s fine - the object still exists and the music keeps playing. If I then go back to the Main Menu, Unity instantiates a second instance of the audio object so I now have two playing, same thing happens a third, forth time (etc) every I return to the Main Menu.
Has anything changed in Unity 3 that would cause this or is it likely a bug?
unity 3 has no longer the restriction of a single compressed audio stream now it will just use cpu in this case and play several of them.
the bug here is your code thats halfbaken and tries to use the singleton pattern (you keep the instance forever and don’t want another one) while avoiding the whole management of it.
you need to add code that checks if there is already another instance of the class and if so destroys this one and returns before it even reaches dontdestroyonload etc
Thanks - I’ve just put the object into a prefab and dropped this script onto the Main Menu camera.
var backgroundMusicPrefab : Transform;
function Start() {
if (!(GameObject.FindWithTag("BackgroundMusic")))
Instantiate(backgroundMusicPrefab, transform.position, transform.rotation);
}
Probably not a very pretty way to do things, but it works.
I think I’ve made some serious mistakes in my learning process and Unity 3 is highlighting them all unfortunately. Not an easy transition
that way is near fine
near cause you use strings and tags instead of looking if there is an instance of that class of the script you use there for example or something similar
PS: just realized that this isn’t in the iphone board. would likely have gotten more attention there.
Is it iPhone specific though? My main reason for even attempting to open the project in Unity 3 is to get it ready for a web build once that option becomes available.
I’ll keep plugging away - I get what you mean re looking for an instance of that class. Will fix it up. The tag was just the first thing that came to mind.
If you really want to be my hero dreamora, maybe you can take a look at this thread for me at some point…