NullReferenceException with PlayerPrefs.GetInt();

Hey everyone!

I’m making Save & Load system, and I keep getting NullReferenceException when I loop through some data and then get it with GetInt.

This works with cash value, however, I want to save int “unlocked” which is 0-1 value, and I want to check it and get all values and set it to all characters in array.

Here is code:

using System;
using UnityEngine;

public class GameData : MonoBehaviour {

	private static readonly string cashKey;

	public void Save () {

		PlayerPrefs.SetInt (cashKey, User.Instance.cash);

		for (int i = 0; i < CharacterMenu.instance.characters.Length; i++) {
	
			PlayerPrefs.SetInt("Character", CharacterMenu.instance.characters*.unlocked);*
  •  }*
    
  • }*

  • public void Load () {*

  •  User.Instance.cash = PlayerPrefs.GetInt (cashKey);*
    
  •  for (int i = 0; i < CharacterMenu.instance.characters.Length; i++) {*
    

_ CharacterMenu.instance.characters*.unlocked = PlayerPrefs.GetInt(“Character”);_
_
}_
_
}_
_
}*_
Thanks.
UPDATE I’ve managed it to work (save and load), but I still get NullReferenceException on this line: for (int i = 0; i < CharacterMenu.instance.characters.Length; i++) { , Any ideas?

Sounds like your character menu array, or instance hasn’t been initialized when you are trying to access either it or the array contained within.

Load seems to be called earlier than the character menu instantiation, thus, causing your null reference error.