I have a “singleton” script that is intended to run for several scenes and then end when a certain scene is loaded. I believe I have this set up to destroy the game object the singleton is a component of when build index 2 is loaded. However, it doesn’t destroy the game object until after index 2 is loaded and then exited. What am I doing wrong here?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SoundtrackSingleton : MonoBehaviour
{
public static SoundtrackSingleton instance;
void Awake()
{
ManageSingleton();
}
void Start()
{
FindObjectOfType<AudioManager>().Play("Well");
}
void Update()
{
int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
if(currentSceneIndex == 2)
{
Destroy(this);
}
}
void ManageSingleton()
{
if(instance != null)
{
gameObject.SetActive(false);
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
}
}