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. Dismiss Notice

DontDestroyOnLoad Example

Discussion in 'Scripting' started by tmendez, Jul 12, 2019.

  1. tmendez

    tmendez

    Joined:
    Oct 12, 2015
    Posts:
    39
    Hi there,

    In the following example: https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html

    the DontDestroy.cs script looks like this:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. // Object.DontDestroyOnLoad example.
    6. //
    7. // This script example manages the playing audio. The GameObject with the
    8. // "music" tag is the BackgroundMusic GameObject. The AudioSource has the
    9. // audio attached to the AudioClip.
    10.  
    11. public class DontDestroy : MonoBehaviour
    12. {
    13.     void Awake()
    14.     {
    15.         GameObject[] objs = GameObject.FindGameObjectsWithTag("music");
    16.  
    17.         if (objs.Length > 1)
    18.         {
    19.             Destroy(this.gameObject);
    20.         }
    21.  
    22.         DontDestroyOnLoad(this.gameObject);
    23.     }
    24. }
    My question is why does it call `Destroy(this.gameObject)` before `DontDestroyOnLoad(this.gameObject)` if there are any gameobjects with the tag `'music'`?

    Thanks
     
  2. Lurking-Ninja

    Lurking-Ninja

    Joined:
    Jan 20, 2015
    Posts:
    9,907
    It is kind of singleton maneuver it ensures that only one gameobject with tag "music" can exist. Hence the obj.Length > 1. If you think about it, when
    - there is 0 game object with tag "music" exists and this gets an Awake call: it won't be Destroyed since the obj.Length == 1, so it gets the DontDestroyOnLoad
    - then in a next scene or on a reload of the current scene there is 1 game object with tag "music" and this game object gets created again (since scene load) the obj.Length will be 2 which is > 1, so the later game object will be destroyed so there can be only one
     
    Joe-Censored and tmendez like this.
  3. tmendez

    tmendez

    Joined:
    Oct 12, 2015
    Posts:
    39
    Oh I see, thanks Lurking-Ninja!