---
title: "How do you add a script to a GameObject in Unity?"
description: "Create a C# script from the Assets menu, then drag it onto a GameObject or use Add Component in the Inspector. Or add it from code with AddComponent."
url: "https://bugsee.com/answers/unity/unity-add-script-to-gameobject/"
---

# How do you add a script to a GameObject in Unity?

Create a script with Assets > Create > C# Script, then drag it onto the GameObject in the Hierarchy, or use Add Component in the Inspector. The file name must match the class name.

```csharp
using UnityEngine;

public class Spinner : MonoBehaviour      // class name must match Spinner.cs
{
    public float degreesPerSecond = 90f;

    void Update()
    {
        transform.Rotate(0f, degreesPerSecond * Time.deltaTime, 0f);
    }
}

// Adding it from code
// var spinner = someObject.AddComponent<Spinner>();
```

- If the script shows as a plain file or the component says "The associated script cannot be loaded", the file name and class name do not match, or the script has a compile error.
- The class must inherit from `MonoBehaviour` to be attached to a GameObject.
- A script can only be added once per GameObject unless it has no `[DisallowMultipleComponent]` attribute.

## Related questions

- [How do variables and the Inspector work in Unity scripts?](https://bugsee.com/answers/unity/unity-variables/)
- [How do you customize script templates in Unity?](https://bugsee.com/answers/unity/unity-script-templates/)
