- Home /
Is it necessary to null an instance on quit?
static var instance : LevelData;
function Awake ()
{
// Find itself
instance = FindObjectOfType(LevelData);
if (instance == null)
Debug.Log ("Could not locate a singleton object in the scene.");
// Retain between scenes
DontDestroyOnLoad(gameObject);
}
// Ensure that the instance is destroyed when the game is stopped in the editor.
function OnApplicationQuit() {
instance = null;
}
I'm trying to understand a JS singleton… I've condensed the basics down — from the unity wiki — into the above code and it works well but I have a niggling question. It has that function: OnApplicationQuit, null the instance — Isn't that redundant? Wouldn't it be emptied upon game quit anyway or am I missing something?
I don't know if it is necessary but it is certainly not a bad idea.
That way you can make sure that any resource/memory is freed, regarding of execution order or other constraints.
The garbage collector is supposed to take care of it. But it's not hurting aanyone to do it :)
But quitting the application would be inherently deleting all instances from being in memory, wouldn't it? o_0
Or do some things get left over in memory when quitting the application? What systems does that happen on?
@Berenger No it doesn't. If a reference is kept to an object it cannot be collected.
@Essential When your run your game inside the editor you share the same memory as the editor, therefore some objects may be leaked. Of course in a standalone, this is not necessary since the virtual machine will release all allocated memory.
Answer by IT_Criminal · Nov 21, 2012 at 12:21 PM
when the editor closes game simulation the garbage collector takes care of everything anyway ... so there is absolutely no reason for this ... i've never done this and i've never had any problems
This is not true for static variables, which is the case here.
i see ... but anyway it's just editor lag ... on the real application everything gets deallocated when the application closes ... you can null stuff if you want ... but it doesn't really help
That's good info to be aware of kryptos. I think rather than going back through all my code and making sure I deallocate every static variable, I'll just keep it simple and leave it out.
Your answer
![](https://koobas.hobune.stream/wayback/20220613084247im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Object reference not set to an instance of an object 0 Answers
Static singleton is (not nullref -empty-) but assigned to "null" in the other Scenes 2 Answers
How to subtract variable from singleton instance? 0 Answers
Accessing Singleton Instance Methods Directly 2 Answers
DontDestroyOnLoad & Singleton 2 Answers