Has anyone encountered GetComponent<>() Failing recently

I’ve been having an issue that randomly pops up from time to time where GetComponent() fails even if the component is on the object the script is attached to and enabled.

While the game is running it just keeps failing when in update, if I click on the object in question in the Scene View GetComponent() stops failing.

Working in Unity 5.1.1f1 currently ( going to update to 5.1.2f1 now )
but it has been happening in recent versions of 4 and in 5.x.x for the last two-ish months now…

Haven’t submitted a bug report yet ( along with one where the ui clicks stop working every play after the first play in the editor ( hasn’t happened in a few weeks ) ) because it happens randomly and is had to reproduce consistently.

No, because but it is not good practice to call GetComponent(s) in Update. GetComponent should be called in Awake or Start and then the result stored in a reference variable. So getComponent is only called once for any give component when the script first starts up. But even still, it shouldnt fail in update if the component exists.

Have something like this in update

if ( scriptName == null )
{
   scriptName=gameObject.GetComponent<scriptType>();
}

So it is only called on the first update

1 Like

Have the same issue when the call is in Start/Awake/OnEnable

Start to phrasing it like this.gameObject.GetComponent<>() - it solved it for me.