I can't add script in unity
I’m a beginner in unity so I got this problem. Here is the script:
I don’t know why but it keep saying that Can’t add script component ‘Player control’ because the script class cannot be found.Make sure that there no compile errors and that the file name and class name match.
![]()
3 Answers 3
Check the file name of the script and make sure it’s the same as the class name. I’ve had this problem before after renaming a script through the editor.
Old question, but I solved this problem using the Help menu and then Reset Packages to defaults.
You either have a compile error in this script, or you have one in a different script. If this is the first time you’re trying to use this script, the entire solution needs to compile before Unity knows about this new class you’re introducing.
Locate your error and correct it before trying to add this script. It could be a compile error or something like a name mismatch like SanSolo suggests.
![]()
You must log in to answer this question.
-
The Overflow Blog
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.9.7.43618
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Can't add script component because the script class cannot be found?
Yesterday I updated unity from unity5 to 2018.2.2f1. Unity scripts are not loading after Update 2018.2.2f1.
Once I try to play the Scene the scripts are not loaded and I can’t add the script again it gives this error:
Can’t add script component ‘CubeScript’ because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match.

![]()
![]()
12 Answers 12
If you still have the old copy of the project, upgrade the Unity project to Unity 2017 first then to 2018.2.2f1.
Here are the few possible reasons you may get this error(Ordered from very likely)
1.Script name does not match class name.
If script name is called MyClass , the class name must be MyClass . This is also case-sensitive. Double check to make sure that this is not the issue. To make sure that’s not the issue, copy the class name and paste it as the script name to make sure that this is not the issue.
Note that if you have have multiple classes in one script, the class name that should match with the script name is the class that derives from MonoBehaviour .
2.There is an error in your script. Since this is an upgrade, there is a chance you’re using an API that is now deprecated and removed. Open your script with Visual Studio and see if there is an error there then fix it. There is usually a red line under a code that indicates there is an error.
3.Bad import with the Unity importer and its automatic upgrade script.
A.The first thing to do is restart the Unity Editor.
B.Right click on the Project Tab then click «Reimport All»
C.If there is still issue, the only left is deleting the problematic script and creating a new one. There is an easier way to do this if the script is attached to many GameObjects in your scene.
A.Open the script, copy its content into notepad.
B.From the Editor and on the Project tab right click on the script «CubeScript», select «Find References In Scene».
C.Unity will now only show all the GameObjects that has this script attached to them. Delete the old script. Create a new one then copy the content from the notepad to this new script. Now, you can just drag the new script to all the filtered GameObject in the scene. Do this for every script effected. This is a manual work but should fix your issues when completed.
Устранение ошибки "Can’t add script component because the script class cannot be found" в Unity: шаг за шагом руководство
Одна из распространенных ошибок, с которой разработчики Unity сталкиваются при добавлении нового скриптового компонента к объекту, называется "Can’t add script component because the script class cannot be found" (Невозможно добавить скриптовый компонент, потому что класс скрипта не может быть найден). Эта ошибка обычно возникает, когда Unity не может найти класс скрипта, на который ссылается компонент.
В этой статье мы предоставим пошаговое руководство по устранению данной ошибки. Следуя приведенным ниже шагам, вы сможете успешно добавить свой скриптовый компонент в Unity.
Шаг 1: Проверьте правильность имени класса скрипта
Первым шагом для устранения данной ошибки следует убедиться, что имя класса в скрипте правильно указано и соответствует ожидаемому значению. Для этого выполните следующие действия:
- Откройте скрипт, на который вы пытаетесь ссылаться в компоненте.
- Убедитесь, что имя класса написано без ошибок.
- Убедитесь, что имя класса точно соответствует имени, которое вы используете для добавления компонента в Unity.
- Если вы не уверены, скопируйте имя класса из файла скрипта и вставьте его в поле имени класса в компоненте Unity.
Шаг 2: Проверьте расположение скриптового файла
Вторым шагом следует проверить, находится ли скриптовый файл в правильном расположении в вашем проекте Unity. Для этого выполните следующие действия:
- Откройте исходный код интегрированной среды разработки (IDE), в которой вы работаете над своим проектом Unity.
- Убедитесь, что скриптовый файл находится в нужной директории или папке проекта.
- Если файл находится в неправильной директории, переместите его в соответствующую директорию проекта.
Шаг 3: Пересоберите проект Unity
Третий шаг — перекомпилирование вашего проекта Unity. Для этого выполните следующие действия:
- Закройте Unity и все связанные с ним процессы.
- Перейдите в интегрированную среду разработки (IDE).
- Выполните пересборку проекта с помощью соответствующих инструментов IDE.
Шаг 4: Проверьте настройки сборки
В некоторых случаях, указанный класс может быть недоступен из-за некорректных настроек сборки проекта Unity. Для устранения этой проблемы выполните следующие действия:
- Откройте окно настроек проекта в Unity.
- Перейдите на вкладку "Player Settings" (Настройки проигрывателя).
- Убедитесь, что все необходимые сборки и настройки скриптов включены и правильно настроены.
- Если вы не уверены, что нужно настроить, проконсультируйтесь с официальной документацией Unity или посетите онлайн-форумы Unity, где опытные разработчики могут помочь вам с правильными настройками.
Шаг 5: Проверьте наличие ошибок компиляции
Последний шаг — проверка наличия других ошибок компиляции в вашем проекте Unity. В случае наличия других ошибок компиляции класс, на который ссылается компонент, может быть недоступным для использования. Чтобы проверить наличие ошибок компиляции:
- Откройте ваш проект Unity.
- Перейдите во вкладку "Console" (Консоль) в Unity.
- Убедитесь, что в консоли отсутствуют какие-либо ошибки компиляции.
- Если вы обнаружили ошибки, исправьте их и повторно выполните шаги 3-5.
После выполнения всех этих шагов вы должны быть способны успешно добавить скриптовый компонент в Unity и избежать ошибки "Can’t add script component because the script class cannot be found".
Надеемся, что это руководство помогло вам устранить данную ошибку в вашем проекте Unity. При возникновении дополнительных сложностей обратитесь к официальной документации Unity или обратитесь за помощью на форумах Unity, чтобы получить дополнительную поддержку и рекомендации от сообщества разработчиков Unity.
Can't add script component because the script class cannot be found?
Can’t add script component because the script class cannot be found?
Yesterday I updated unity from unity5 to 2018.2.2f1. Unity scripts are not loading after Update 2018.2.2f1.
Once I try to play the Scene the scripts are not loaded and I can’t add the script again it gives this error:
Can’t add script component ‘CubeScript’ because the script class
cannot be found. Make sure that there are no compile errors and that
the file name and class name match.

Solution – 1
If you still have the old copy of the project, upgrade the Unity project to Unity 2017 first then to 2018.2.2f1.
Here are the few possible reasons you may get this error(Ordered from very likely)
1.Script name does not match class name.
If script name is called MyClass , the class name must be MyClass . This is also case-sensitive. Double check to make sure that this is not the issue. To make sure that’s not the issue, copy the class name and paste it as the script name to make sure that this is not the issue.
Note that if you have have multiple classes in one script, the class name that should match with the script name is the class that derives from MonoBehaviour .
2.There is an error in your script. Since this is an upgrade, there is a chance you’re using an API that is now deprecated and removed. Open your script with Visual Studio and see if there is an error there then fix it. There is usually a red line under a code that indicates there is an error.
3.Bad import with the Unity importer and its automatic upgrade script.
A.The first thing to do is restart the Unity Editor.
B.Right click on the Project Tab then click “Reimport All”
C.If there is still issue, the only left is deleting the problematic script and creating a new one. There is an easier way to do this if the script is attached to many GameObjects in your scene.
A.Open the script, copy its content into notepad.
B.From the Editor and on the Project tab right click on the script “CubeScript”, select “Find References In Scene”.
C.Unity will now only show all the GameObjects that has this script attached to them. Delete the old script. Create a new one then copy the content from the notepad to this new script. Now, you can just drag the new script to all the filtered GameObject in the scene. Do this for every script effected. This is a manual work but should fix your issues when completed.
Solution – 2
One more thing which might help apart from other answers
- Make the class which inherits from the MonoBehaviour the first class in the file. It fixed this issue for me.
Solution – 3
Posting here for historic purposes and if someone from Google ends up here, I strictly had the same problem (I’m on Windows 10) and here’s how I fixed it :
- If you click on the Console, you should see a blank error. Don’t worry, it’s a Editor bug, and you can see the Editor Log by selecting the console’s window dropdown and selecting Open Editor Log.
For me, the problem was that “ToolsRoslyncsc” could not be found, something that Unity uses to compile C# files.
- I opened C:Program FilesUnityHubEditor2019.2.14f1EditorDataToolsRoslynScriptsunity_csc.bat and I added “.exe” to the line «%APPLICATION_CONTENTS%ToolsRoslyncsc» /shared %*
(This line should now be : «%APPLICATION_CONTENTS%ToolsRoslyncsc.exe» /shared %* )
Now it works perfectly.
Solution – 4
Checking the console bugs and fix them is a good way to solve the problems “Can’t add script component because the script class cannot be found?”, although the bug seems to be irrelevant.
This works for me when I fix a bug in the other script.
Solution – 5
for me I found out it was a script that I wasn’t using which was linked to the player and other scripts that I deleted.
Solution – 6
I’m completely new to Unity and game development, but I found that making the error true by entering an incorrect name, then entering the right one seems to "trick" Unity into fixing its error.
Solution – 7
Here, is some reason why that’s heaping.
1 . Your Script Name And your class name isn’t same.
2 . May be there is an error in your script.
Here, is the few way to resolve it.
1 . Make a same name of script and class in to this script.
2 . find there is the error? and try to resolve it.
Solution – 8
For me, the problem was that there was an error in another script.
Once I fixed the error, I could FINALLY attach my other scripts onto my gameobjects.
Solution – 9
I had the same error show up but for different reasons (in case someone ends up here from google).
I was a beginner and named my file with a space in it. I got the same error after that. Make sure to NOT include spaces in your C# script.
Solution – 10
I just had this issue where I had a perfect script, no errors, and the same name as it should be but no matter what it wouldn’t let me add it to a gameObject.
There was another script that was completely unrelated but it had an error in that and somehow that prevented me from adding my good new script.
Solution – 11
Like some folks already posted here – the issue might be of a different code.
I was trying to add a script that was referenced by another one which had errors – it doesn’t tell you that is the reason, although visual studio kinda suggests it by showing you the errors in the open script.
Just delete the bigger (errored) script and start adding to the unity project from the basic ones.
Solution – 12
I had this issue where I had a good script, no errors, good name, restarting unity, following a tutorial exactly but still had this issue.
The way I fixed this is just deleting this buggy script file and creating it again. It fixed my problem perfectly! Now I could add the script to my game object with no such errors!