- Home /
Question by
Sam_da_dev · Sep 05, 2020 at 03:57 AM ·
scenescenesmusicdontdestroyonload
My music duplicates and gives an error
I did a script for playing music between scenes, the problem is that when I go to a different scene the music play itself again and gives an error in the console saying "The object of type 'AudioSource' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object". here is the code :
public class MusicPlay : MonoBehaviour
{
public static MusicPlay musicplay;
public bool Always;
public GameObject music;
void Awake() {
if (musicplay == null)
{
DontDestroyOnLoad(gameObject);
musicplay = this;
}
else if (musicplay != this)
{
musicplay = null;
Destroy(gameObject);
}
}
}
help would be really appreciated
Comment
Answer by AdrianTEC · Sep 05, 2020 at 08:39 PM
When you change the scene all objects in the previous scene are destroyed, the object who has the audio source too, that explains the error you re receiving. I think this could help you Continuous AudioSource in DontDestroyOnLoad