Script component disappears randomly in runtime

I have already searched for it, but all I can find is about this error appearing when the game is played or something like it.
That’s not my case.

My game works fine for some time, but then, randomly, I get this error:

“The referenced script on this Behaviour is missing!”

After that I get some NullReferenceException.
Apparently my script components disappear.

This has happened to more than one script, and I can’t see any link between them.

What could be causing this?

This happens when you have a script attached to an object (in the scene or a prefab) and you

  • deleted your actual script file from your project.
  • you moved it to a different folder outside of Unity without the corresponding meta file.
  • you renamed either the class or the file the class is defined in so the script can no longer be used.

To fix this problem, first make sure your script and the file it contains both have the same name. Now you have two options:

  • Either just delete the old component from your gameobjects and re-add the script.
  • If you originally had many settings and you don’t want to loose those settings, you can keep the broken component and re-link the script file. To do this switch your inspector into debug mode (context menu at the top right of the inspector). Once in debug mode your component should have a script field. Now you can simply drag the correct script onto that variable and the component should work again. Just don’t forget to switch the inspector back to normal mode.