Search code examples
unity-game-enginein-app-purchase

Can't load the In App Purchases when reloading the same scene


I have an issue with my In App Purchases manager. I load my scene and can successfully purchase items. I go to a new scene in game and then back to that scene and now it says...

`MissingReferenceException: The object of type 'IAPManager' 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.`and then points my to this line

moneyController = GetComponent<MoneyController>();

Why does it crash at that point? Do I need to add DontDestroyOnLoad or something? I'm not familiar with that or how to use it though. Am I missing something simple? Here are some more code snippets that may or may not prove useful. This code is from a tutorial hence why it's difficult for me to pin point the issue.

public static IAPManager Instance{set;get;}

private void Awake() { Instance = this; }


Solution

  • you have to put in DontDestroyOnLoad this way you will not get any error for same. below is the code that you can use.

    private static IAPManager instance;
    public static IAPManager Instance
    {
        get
        {
            if (instance == null) 
            {
                GameObject o = new GameObject ("IAPManager");
                instance=o.AddComponent<IAPManager>();
                DontDestroyOnLoad (o);
    
    
            }
            return instance;
        }
    }