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.

Making Objects Float Up & Down in Unity

Ever wanted to make an object float up and down while spinning in Unity? Well, I’ve written a script for that.

End Result of Script


  1. Select an object in your Unity project.
  2. Add Component > New Script
    1. Name: Floater
    2. Language: C-Sharp
  3. Edit the script
  4. Copy & Paste the code below into your script editor.
  5. Save the script.
  6. Tweak settings to your heart’s content

// Floater v0.0.2
// by Donovan Keith
// [MIT License](https://opensource.org/licenses/MIT)

using UnityEngine;
using System.Collections;

// Makes objects float up & down while gently spinning.
public class Floater : MonoBehaviour {
	// User Inputs
	public float degreesPerSecond = 15.0f;
	public float amplitude = 0.5f;
	public float frequency = 1f;

	// Position Storage Variables
	Vector3 posOffset = new Vector3 ();
	Vector3 tempPos = new Vector3 ();

	// Use this for initialization
	void Start () {
		// Store the starting position & rotation of the object
		posOffset = transform.position;
	// Update is called once per frame
	void Update () {
		// Spin object around Y-Axis
		transform.Rotate(new Vector3(0f, Time.deltaTime * degreesPerSecond, 0f), Space.World);

		// Float up/down with a Sin()
		tempPos = posOffset;
		tempPos.y += Mathf.Sin (Time.fixedTime * Mathf.PI * frequency) * amplitude;

		transform.position = tempPos;