Function being called from another script resulting in NullReferenceException on one variable.

I’m running into a problem that is really stumping me. I have a fully-functional “menu refresh” function that I use a lot, which calls a function and passes in three variables.

The function in question:

private void GenerateMusicPanelContent()
    {
        FillSongPanel(OwnedSongsList, _panelContents[0].transform, "music");
    }

This function is called both from inside and outside the script: once in Start() and once in another public function that is called from a Unity IAP ProcessPurchase function.

The script works perfectly in Unity in both instances, but when I build to iOS, and call the function from the IAP purchasing script (the menu is to refresh after a purchase), I get a NullReferenceException error. On iOS, I do not get the error when this function is called from the Start() function. It also doesn’t give an error when I set up a Button which calls the same function.

Specifically, the _panelContents[0] value returns “null” when debugging, only when calling from the ProcessPurchase script when built to iOS (it throws zero errors in engine, or when being called from Start()). The other two variables do not return null exceptions. Nevertheless, this variable is defined in the public variables at the top of the script, and assigned in the editor.

And I simply don’t even know where to start looking for this. The function doesn’t throw any errors in-engine, only through the purchasing script, on a device. The discussion page for IAPs ensured me this is a scope issue, which I believe it is, but I can’t seem to replicate the problem in-engine, so I’m not sure where to look for this.

After pulling my hair out for the last few hours, it appears that… “Save Project” solved the issue? I use the save shortcut (command+s) pretty regularly, and that allowed me to make modifications to the project, but something about the setup here was not going through apparently until I specifically went to the menu and chose “Save Project”. Not sure about that…

These things are rare, but they can happen. Here is one specific way I’ve seen things like this:

  1. you create a public variable to drag stuff into in the inspector:
public GameObject MyDoodleberry;
  1. you drag your doodleberry reference in, work for a while, make some prefabs, use them in scenes, etc.

  2. You decide you want to change your doodleberry reference into some other type, without renaming it:

public Transform MyDoodleberry;

NOTE: you have changed the type out “under” Unity, and what is in the scene MIGHT continue working, but once reloaded into a fresh scene (As it will be on the target build), it fails out because it cannot cast the GameObject to a Transform.

Glad to hear you solved it!

2 Likes