Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question How to make DontDestroyOnLoad stop duplicating game objects!

Discussion in 'Scripting' started by itsdandd, Jul 6, 2020.

  1. itsdandd

    itsdandd

    Joined:
    Jan 6, 2020
    Posts:
    44
    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:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Music : MonoBehaviour
    6. {
    7.      void Awake()
    8.     {
    9.         GameObject[] objs = GameObject.FindGameObjectsWithTag("Music");
    10.         if (objs.Length > 1)
    11.             Destroy(this.gameObject);
    12.         DontDestroyOnLoad(this.gameObject);
    13.     }
    14. }
    15.  
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    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.

    Code (CSharp):
    1. public class Music : MonoBehaviour
    2. {
    3.     public static Music Instance;
    4.  
    5.     void Awake()
    6.     {
    7.         if(Instance == null)
    8.         {
    9.             Instance = this;
    10.             return;
    11.         }
    12.  
    13.         Destroy(gameObject);
    14.     }
    15. }
     
    itsdandd and Yoreki like this.
  3. itsdandd

    itsdandd

    Joined:
    Jan 6, 2020
    Posts:
    44
    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.
     
    Last edited: Jul 7, 2020