- Home /
I am using DontDestroyOnLoad Script and when I return to the Menu scene the buttons do not work but the music continues to play
public class DestruirSom : MonoBehaviour {
public static DestruirSom mp;
void Awake ()
{
if (mp == null)
{
mp = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
}
Answer by JavierRuidoRosa · Jul 10, 2018 at 07:39 AM
If the buttons use methods from this code, it's normal they stop working when you enter the menu scene again.
You see, when using the button inspector to assign a method to the OnClick call, you need to assign them a reference to the GameObject that has the script with that method you need.
When you create a Singleton for that object (static reference to itself, can't be more than one instance), and you make it persistent with the DontDestroyOnLoad method, the next time you enter the menu scene there will be another instance of your object. That's why you have to make sure in Awake() you destroy the second instance.
The problem is that this second instance, as it is the one included in the scene, is the one your buttons are trying to access for the methods, and you're destroying it.
You should not have code used by the buttons in a persistent script. Put those methods in other script and make a new non-persistent GameObject in that scene. Hope this helps!
Answer by manishsaini74 · Jul 10, 2018 at 10:00 AM
When you enter from game to Main Menu and come back to game it pause the previous scene you can use Time.timeScale = 1.0f; in Main Menu code which will resume your game.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class StartGame : MonoBehaviour {
// Use this for initialization
public void gameStart () {
SceneManager.LoadScene("Main");
Time.timeScale = 1.0f;
}
}
You can use this code for your Start button.
Your answer
Follow this Question
Related Questions
Changing scene causes null reference exceptions 3 Answers
Get Text from an Input Field on one scene and use it as a text on another scene Unity c# 0 Answers
To pass a variable between scenes should I use scriptableobject or static ? 1 Answer
How do I transfer a gameobject created in one scene to another scene AND use it in a c# script? 1 Answer