Help. Unity crashes when code is run.

for some reason when i run my save() function unity crasshes. Heres the code for the save:

public void save () {
		init ();
		foreach (var key in Itemdictionary) {
			PlayerPrefs.SetFloat (key.ToString() + "_cost", getdict (key.ToString(), "cost"));
		
			PlayerPrefs.SetFloat (key.ToString() + "_item", getdict (key.ToString(), "item"));
			Debug.Log (key.ToString () + PlayerPrefs.GetFloat (key.ToString() + "_cost").ToString());
		}
		//TODO make foreach save loop for dict and save other data
	}

And here is the init() function that is called:

void init(){
		if (Itemdictionary == null) {
			setdict ("test", "cost", 100);
			setdict ("testtt", "cost", 200);
			setdict ("testt", "cost", 130);
			Itemdictionary = new Dictionary<string, Dictionary<string, float>> ();
			//TODO fix costs in init.
		}
			
	}

And heres the setdict() function:

 void setdict (string name, string datatype, float value) {
    		init ();
    		if (Itemdictionary.ContainsKey(name) == false) {
    			Itemdictionary [name] = new Dictionary<string, float> ();
    		}
    		Itemdictionary [name] [datatype] = value;
    
    	}

Anny help is apriciated thanks :slight_smile:

In your setDict method use:

void setdict (string name, string datatype, float value) {
             if (ItemDictionary == null)
                 Itemdictionary = new Dictionary<string, Dictionary<string, float>> ();

             if (Itemdictionary.ContainsKey(name) == false) {
                 ItemDictionary.Add(name, new Dictionary<string, float> ()); 
             }

             if (!Itemdictionary[name].Contains(datatype))
                 itemDictionary[name].Add(datatype, value);
             else 
                 Itemdictionary [name] [datatype] = value;
         }

Then call your init() without setting the dictionary. The way you’re doing it is causing an infinite loop.

init => setdict

setdict => init

init => setdict

And it never reaches the point where the dictionary gets initialized…
And in your save() method you’re using the dictionary all wrong. Dictionaries are iterated over KeyValuePairs.

I’d suggest reading up on Dictionaries a bit more before trying to work with this. C# Dictionary Examples - Dot Net Perls

I assume with “crash” you mean “raises a NullReferenceException”. If it is a hard process crash, then you should report this to Unity via the BugReportTool.exe next to the Unity.exe (or by selecting “Help/Report Bug” from the Editor).

So for the NullReferenceException you should get:

Your init() function first calls to “setdict” and then initializes the variable “Itemdictionary”. But setdict accesses the Itemdictionary variable.

Just move the initialization of Itemdictionary before all “setdict” calls.