- Home /
Singleton's property is always null
The problem is that when trying to check CurrentMenu
property from MainCameraMove
it always returns null even if previously _currentMenu
definitely was set by invoking ShowMenu
function. Does unity somehow clears objects on its like?
public class MenuManager {
private Menu _currentMenu;
public Menu CurrentMenu
{
get { return _currentMenu; }
set { _currentMenu = value; }
}
private static MenuManager instance = null;
public static MenuManager Instance
{
get
{
if (instance == null)
{
instance = new MenuManager();
}
return instance;
}
}
public void ShowMenu(Menu menu)
{
HideAllMenus();
_currentMenu = menu;
menu.IsOpen = true;
}
}
public class MainCameraMove : MonoBehaviour
{
if (MenuManager.Instance.CurrentMenu == null)
{...}
}
UPDATE: Thanks everyone for suggestions. I've found the bug. Other function was called from Update() that instantly got the currentMenu
property to null
first of all, you should be doing this in Show$$anonymous$$enu:
Current$$anonymous$$enu = menu;
ins$$anonymous$$d of:
_current$$anonymous$$enu = menu;
right now it'll do the same thing, but you might want to add side effects (like logging or updating other properties) of the setter in the future, and then setting _current$$anonymous$$enu will sidestep those.
To debug this issue, ensure that you never set _current$$anonymous$$enu anywhere outside of Current$$anonymous$$enu's setter, and do the setter like this:
private $$anonymous$$enu _current$$anonymous$$enu;
public $$anonymous$$enu Current$$anonymous$$enu
{
get { return _current$$anonymous$$enu; }
set {
Debug.Log("Setting current menu to: " + value);
_current$$anonymous$$enu = value;
}
}
Answer by AlwaysSunny · Feb 23, 2015 at 04:09 PM
I like this singleton class quite a bit. Just derive your class in the way indicated below, and the script will function as a singleton. (As a gameobject, but you could change this if you wanted to. I like my singletons on game objects, simply b/c it exposes its instance to you in the inspector.)
HasteBin to code for Singleton script, place anywhere in project
Derive your would-be singleton classes from it like so:
public class MenuManager : Singleton<MenuManager> {
public int thisMember = 2;
}
and access its members from anywhere with:
MenuManager.Instance.thisMember = 1;
Answer by Jessespike · Feb 23, 2015 at 05:29 PM
Make your manager class a MonoBehaviour, add it to scene.
public class MenuManager : MonoBehaviour{
instance is itself.
public static MenuManager Instance { get { if (instance == null) { //instance = new MenuManager(); instance = this; } return instance; } }
Put MainCameraMove into it's own .cs file