I am using a DontDestroyOnLoad Script for seamless music in between scenes and 2 buttons (One too set.active and one to deactivate). When I deactivate the music game object and then go back the the home scene a new music object is created. Is there a way to stop this? Any help is welcome.
Thanks!
DontDestroyOnLoad Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Music : MonoBehaviour
{
void Awake()
{
GameObject[] objs = GameObject.FindGameObjectsWithTag("Music");
if (objs.Length > 1)
Destroy(this.gameObject);
DontDestroyOnLoad(this.gameObject);
}
}
FindObjectsWithTag will not find objects set to DontDestroyOnLoad as they are in their own special scene.
It sounds like you want a singleton. Do this and use Music.Instance to access the methods you want to use.
public class Music : MonoBehaviour
{
public static Music Instance;
void Awake()
{
if(Instance == null)
{
Instance = this;
return;
}
Destroy(gameObject);
}
}
Thanks for replying! This worked! However this brought up another problem. If I set the object as not active and then go the the next scene and then come back and try to set it active it says game object missing.