I am struggling to write a script to perform the title objective.
I have 2 levels with a “BGM” object with the same script but a different audio source. Dying on a level reloads the scene and reaching the end loads the next scene on the build index.
basically i want the music to keep going when you die, but not on the next level.
Here is what I have so far for the BGM script:
using UnityEngine;
using UnityEngine.SceneManagement;
public class PersistSameLevel : MonoBehaviour
{
int bi;
static GameObject persist;
int scene;
void Start()
{
bi = SceneManager.GetActiveScene().buildIndex;
if (scene != 0)
{
if (scene != bi)
{
Destroy(gameObject);
persist = null;
Debug.Log("not new, different scene");
}
}
else
{
if (persist == null)
{
persist = gameObject;
scene = bi;
Debug.Log("new, no persist");
}
else
{
if (scene == bi)
{
Destroy(gameObject);
Debug.Log("new, persist, same scene");
}
else
{
persist = gameObject;
scene = bi;
Debug.Log("new, persist, different scene");
}
}
}
}
void Update()
{
DontDestroyOnLoad(gameObject);
}
}
I imagine a flow chart but cant seem to get the timing down.
if:
new and nothing leftover - stay
old and same scene - new is destroyed
old and new scene - self destroy and new one sees nothing leftover