Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved problem with singleton script

Discussion in 'Scripting' started by aetztztztzzew, May 14, 2020.

  1. aetztztztzzew

    aetztztztzzew

    Joined:
    Apr 12, 2018
    Posts:
    39
    Hi!
    I have instance attached to gameobject in main menu scene. When i change between scenes and return back to main menu scene 2 instances of class are active. How can i change my code to make only one istance of class available at time?
    Thanks for helping!



    Code (CSharp):
    1.  
    2. public class soundManager : MonoBehaviour
    3. {
    4.    
    5.    public static soundManager instance;
    6.  
    7.     private void Awake()
    8.     {
    9.         if (instance == null)
    10.         {
    11.             instance = this;
    12.         }
    13.         else if (instance != null )
    14.         {
    15.             Destroy(this);
    16.  
    17.         }
    18.         DontDestroyOnLoad(this);
    19.  
    20.        
    21.      
    22.     }
    23.  
    24.  
    25.  
    26.     }
    27.  
    28.  
    29.  
    30.  
    31. }
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,893
    On line 15 instead of
    Code (CSharp):
    1. Destroy(this);
    you probably want:
    Code (CSharp):
    1. Destroy(this.gameObject);
     
    aetztztztzzew likes this.
  3. aetztztztzzew

    aetztztztzzew

    Joined:
    Apr 12, 2018
    Posts:
    39
    Thanks! Solved