- Home /
Using singleton & DontDestroyOnLoad to keep a menus state.
Apologies in advance if this is a trivial question. I have a "Menu" scene that has a bunch of navigation to it and its to my understanding that if I want to save my scene 'state' I need to make it a singleton and use DontDestroyOnLoad so that on returning back to my "Menu" scene from whichever other scene I was in, it will be where I left it and not right back at the beginning again. I created the singleton by using this:
public class SingletonTest : MonoBehaviour
{
public static SingletonTest Instance { get; private set; }
private void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
}
I added that script to a Manager gameObject and referenced my menu (Canvas) by using
public class ManagerTesting : MonoBehaviour
{
public GameObject Menu;
void Start ()
{
Menu = SingletonTest.Instance.gameObject;
}
}
I thought that with these two it would solve my problem, but on loading my Menu scene from anywhere else it is back at the beginning again.
Any advice would be great, thanks
Answer by hexagonius · Dec 10, 2018 at 07:21 PM
SingletonTest needs to be attached to the root gameobject of your menu, done.