How to solve “Can’t Add Script” in Unity

Introduction

In this article we look at the causes of the “Can’t Add Script” error in Unity in order to understand why it occurs and identify what actions to take to fix it.



If you prefer to watch a video I have the right video for this topic:


Why do the “Can’t Add Script” Error occur in Unity?

This error in which we are not allowed to add a Script or component to a GameObject can arise for two reasons.

Case 1: The name of the script and the name of the class it defines do not match

The first one is that the name of the Script, that is to say, the name of the file with extension “.cs” does not match the name of the programming class that is defined inside it. This usually happens when we create a Script and then change the name of the file without doing a Refactoring process.

To solve this problem first we must identify the Script that has conflicts, this can be done with the information provided by the “Can’t Add Script” error window that appears when we try to add the Script with conflicts to a GameObject. If you do not remember which Script produced the error, you can create an Empty GameObject and start adding each of the Scripts until the error appears.

Once we know which is the Script that generates the “Can’t Add Script” error, we open it and we locate the part of the class definition, which begins as follows:

public class NameOfTheClass …

The name of the class is the name that has to match the name of the file, so what you can do is modify the name of the class to match the name of the file, or modify the name of the file to match the name of the class.

Once this problem is solved it will be possible to add the Script to a GameObject. If you need to rename the Script the best way is to right click on the “NameOfTheClass” name and then click on “Rename”, this will make Unity modify that name in all the places where that Script is used.

Case 2: The script was created having errors in the console

The second reason why the “Can’t Add Script” error occurs in Unity is when new Scripts are created while there are errors in console, in general these are syntax errors (errors in writing the code). The reason in this case is that if there are errors in console, Unity can not compile, therefore if we create a new Script at this point, even if the file has been created, the programming class can not be added to the engine, in other words Unity will not know that this Script exists until it compiles.

The solution in this case is to solve all the errors in the console, this will make Unity compile and register the new Script. From that point on you will be able to assign the Script to a GameObject.

Scroll to Top
Secured By miniOrange