I have code that looks like this.
public static Dictionary<int, Action> functionsMap;
void Function()
{
if (!isDictionaryInitialized)
{
functionsMap = new Dictionary<int, Action>();
functionsMap.Add(1, () => StartCoroutine(Function1()));
functionsMap.Add(1, () => StartCoroutine(Function2()));
}
}
void CheckForFunction()
{
var r = currentFunctionNumber;
if (functionsMap.TryGetValue(r, out currentAction)) { currentAction(); }
}
The code works fine when I start my program. However if I go to another scene and then return to it, I get this error.
"MissingReferenceException: The object of type 'ScriptName' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object."
The problem is I have never destroyed the object. Initially I didn't have bool isDictionaryInitialized
and I defined the new Dictionary
outside of the Function because I thought the error was related to my program trying to access a Dictionary
that was deleted after the scene was closed. I get the same problem with or without the bool, and regardless of where I define the Dictionary.
What is causing this, and what is the reason so I can avoid making the same mistake?
Edit: This question was marked as duplicate, but the link I don't believe applies to my situation, or if it does I don't understand how. It says static objects are not reloaded on a scene change, and the Dictionary is defined as a static object. I also tried changing it to non-static and the result is the same.
I have dozens of gameobjects in my code and don't have this issue with any other object, so I assume the problem is related to how the dictionary object is defined. Is there a way to keep the Dictionary object from being destroyed on scene change? I don't have it as a game object in the scene, it's just defined in the code itself as a public static Dictionary. Could someone tell me what I need to do differently please and thank you?