Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. 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:
    48
    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:
    48
    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