NullReferenceException from within GetComponent


I seem to be getting a NullReferenceException using the GetComponent function. This is not a case of GetComponent returning a null value, which would happen if the component didn’t exist on the game object. It’s literally from the GetComponent function. Stack trace from a build (without developer mode so line numbers aren’t visible):

at (wrapper managed-to-native) UnityEngine.Component:GetComponent (System.Type)

at UnityEngine.Component.GetComponent[PhotonView] () [0x00000] in <filename unknown>:0

at PhotonView.Get (UnityEngine.Component component) [0x00000] in <filename unknown>:0

at Photon.MonoBehaviour.get_photonView () [0x00000] in <filename unknown>:0

at CombuMultiplayerRelay.GrantAchievement (System.String achievementId, Single percentageAdded, .CreatureFSM player) [0x00000] in <filename unknown>:0

Does anyone know what could possibly cause this? Is it a bug in Unity? I don’t think it should be possible to get an exception from a Unity API function like this.

My code just tries to access Photon’s “photonView” component and send an RPC.

Edit: We’re on 4.7.2f1

I figured it out. This is what you get if you try to call GetComponent on a game object that has been destroyed. It only happens like this in a build - in the editor you get a much more helpful error:

MissingReferenceException: The object of type ‘GameObject’ has been destroyed but you are still trying to access it.

This seems to be the case in Unity 5 still.

I had the same error and thought I’d post an answer here since this is the first thing that comes up in google. My code was

if (x != null)
    var y = x.GetComponent<Y>();

And I changed it to

if (x.gameObject != null)
    var y = x.GetComponent<Y>();