0
0
UnityDebug / FixBeginner · 4 min read

How to Fix Script Not Working in Unity: Common Causes & Solutions

If your Unity script is not working, first check that the script is attached to a GameObject and that the class name matches the file name exactly. Also, ensure there are no compile errors in the console and that the script inherits from MonoBehaviour to run properly.
🔍

Why This Happens

Scripts in Unity often don't work because the script is not attached to any GameObject, or the class name inside the script does not match the file name. Another common cause is missing the MonoBehaviour inheritance, which is required for Unity to recognize and run the script. Compile errors in the script also prevent it from running.

csharp
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    void Start()
    {
        Debug.Log("Game Started");
    }
}

// Filename: playercontroller.cs (incorrect casing)
Output
Error: The script class 'PlayerController' must be defined in a file named 'PlayerController.cs'
🔧

The Fix

Rename the script file to exactly match the class name, including capitalization. Attach the script to a GameObject in the scene by dragging it onto the object in the Unity Editor. Make sure the script inherits from MonoBehaviour and there are no compile errors in the console.

csharp
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    void Start()
    {
        Debug.Log("Game Started");
    }
}
Output
Game Started
🛡️

Prevention

Always name your script files exactly as the class name inside, including uppercase and lowercase letters. Attach scripts to GameObjects to make them active in the scene. Regularly check the Unity Console for errors and fix them promptly. Use Unity's built-in linting and code analysis tools to catch issues early.

⚠️

Related Errors

  • Script not showing in Inspector: Usually caused by missing MonoBehaviour inheritance or compile errors.
  • NullReferenceException: Happens when you try to use a component or object that is not assigned.
  • Script execution order issues: Can cause unexpected behavior if scripts depend on each other.

Key Takeaways

Ensure script file name matches the class name exactly, including case.
Attach your script to a GameObject in the Unity Editor to activate it.
Inherit from MonoBehaviour for Unity to run your script methods.
Fix all compile errors shown in the Unity Console before running.
Use Unity's console and linting tools regularly to catch issues early.