I Just Copy / Pasted a Script from the Unity Docs, Why isn’t it Working?

I just tried to copy/paste a script from the Unity Website – specifically a script for quitting the game when the player presses Escape. But then it didn’t work… what went wrong? Here’s the process I went through to discover and correct the issue:

  1. I created a new script called “GameController”

  2. I pasted in the code from the website:

  3. but for some reason, it didn’t work.

    The associate script can not be loaded. Please fix any compile errors and assign a valid script.

  4. I tried removing and re-adding the script, and got this error:

    Can't add script component 'GameController' because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match.

  5. After a bit of poking, I disovered it was this line that got me in trouble:

public class ExampleClass : MonoBehaviour {

What’s wrong with this line? The filename was GameController.cs but the class name was ExampleClass. So, how do we fix it? Either rename your file to ExampleClass.cs or modify the code to match the name of the script (which is what I recommend):

public class GameController : MonoBehaviour {

This will also sometimes happen when you rename a script file, because Unity isn’t smart enough to refactor (aka auto-update the names in) your source code.

Leave a Comment