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

Unity singelton property is null when switching scenes

Discussion in 'General Discussion' started by TheMurderOne, Jan 12, 2022.

  1. TheMurderOne

    TheMurderOne

    Joined:
    Aug 14, 2021
    Posts:
    2
    Hello,

    I am new to Unity and C# and for school assignment I have to make a simpel demo game. I wanted to use a singleton pattern to keep track of simple user data when switching scenes, such as character image and player lives. However, when I switch scenes, the instance property is null. I was curious why that was and I used examples I found off the internet, but i can't figure it out. I hope you can help me, thanks in advance.

    Code (CSharp):
    1. public class Player : MonoBehaviour
    2. {
    3.     private static Player playerInstance;
    4.  
    5.     public Image PlayerImage { get; set; }
    6.  
    7.     public static Player Instance { get { return playerInstance; } }
    8.  
    9.  
    10.     private void Awake()
    11.     {
    12.         if (playerInstance != null && playerInstance != this)
    13.         {
    14.             Destroy(this);
    15.         } else {
    16.             playerInstance = this;
    17.             DontDestroyOnLoad(gameObject);
    18.         }
    19.     }
    20. }
    The code from the first scene:

    Code (CSharp):
    1.     public void StartGame()
    2.     {
    3.         SceneHandler.LoadNextScene();
    4.         Player.Instance.PlayerImage = character;
    5.     }
    Code from the second scene:

    Code (CSharp):
    1.     void Start()
    2.     {
    3.         Debug.Log(Player.Instance.PlayerImage); // null
    4.         DisplayText();
    5.  
    6.     }
    Edit: Sorry, I see I posted in the wrong category
     
    Last edited: Jan 12, 2022
  2. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,509
    What happens in LoadNextScene? Do you get any errors in the Console?
     
  3. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Code (CSharp):
    1.     private void Awake()
    2.     {
    3.         if (playerInstance != null && playerInstance != this)
    4.         {
    5.             Destroy(this);
    6.         } else {
    7.             playerInstance = this;
    8.             DontDestroyOnLoad(gameObject);
    9.         }
    10.     }
    Do you have a second copy of the player in your other scene? If you do, the first check will be true, and it will destroy your player, which would lead to the error you are getting.