I am trying to preserve my character during scene changes using DontDestroyOnLoad(), but the character is being destroyed between the menu scene and the actual game even thought I have said DontDestroyOnLoad(gameObject).
Here is a picture of the Hierarchy and the Game Manager.
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; }
}
void Awake(){
//For the GameManager
DontDestroyOnLoad(gameObject);
//For the Characters
for(int i = 0; i < characters.Length; i++){
DontDestroyOnLoad(characters[i]);
}
}
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
I have tried
void Awake(){
//For the GameManager
DontDestroyOnLoad(gameObject);
//For the Characters
for(int i = 0; i < characters.Length; i++){
DontDestroyOnLoad(characters[i]);
}
Instead of
if (instance == null)
{
instance =this;
DontDestroyOnLoad(gameObject);
}
else{
Destroy(gameObject);
}
With the first one, the Gameplay wouldn't load and with the second one the scene would load but the characters get destroyed on load.