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

← Unity answers

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.

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

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required