Home > Blockchain >  DontDestroyOnLoad Unity 2D C#
DontDestroyOnLoad Unity 2D C#

Time:07-23

I am new to unity and C#. Currently, I am following a tutorial (here is the link : https://www.youtube.com/watch?v=gB1F9G0JXOo&list=RDCMUC8butISFwT-Wl7EV0hUK0BQ&start_radio=1&t=12956s). I have almost reached the end( towards 7:15:06 ) but I have run in to a problem. I presume that the character is being destroyed while I am changing between the menu scene and the actual game even thought I have said DontDestroyOnLoad. Anyway, here are the codes :

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{   
    public static GameManager instance;

    [SerializeField]
    private GameObject[] characters;

    private int _charIndex;
    public int CharIndex
    {
        get{ return _charIndex; }
        set{ _charIndex = value; }
    }

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad (gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }

    private void OnEnable()
    {
        SceneManager.sceneLoaded  = OnLevelFinishedLoading;
    }

    private void OnDisable()
    {
        SceneManager.sceneLoaded -= OnLevelFinishedLoading;
    }


    void OnLevelFinishedLoading(Scene scene, LoadSceneMode mode)
    {
        if (scene.name == "Gameplay")
        {
            Instantiate(characters[CharIndex]);
        }
    }
} // class```


  [1]: https://i.stack.imgur.com/MqJMA.png

CodePudding user response:

Instance is uninitialized and will always be null on load. You need instance = this; outside of the if statement in Awake()

Each time Awake() executes, you are calling Destroy(gameObject);

Edit: Because the picture shows that the GameManager class is on a separate objects and you are trying to preserve the characters, you need to call DontDestroyOnLoad for each one.

void Awake(){
    //For the GameManager
    DontDestroyOnLoad(gameObject);
    
    //For the Characters
    for(int i = 0; i < characters.length; i  ){
        DontDestroyOnLoad(characters[i]);
    }
}

CodePudding user response:

DontDestroyOnLoad only works for root GameObjects or components on root GameObjects. You are trying to not destroy an array of gameobjects which I am not sure can be done unless you have the gameobjects in the Hierarchy as a root object and the gamemanager script attached to it.

  • Related