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.
In the following video you can see a brief description on how to solve the «Can’t Add Script» error in Unity:
ABOUT THIS VIDEO
In this video we see how to solve «CAN’T ADD SCRIPT» error in Unity through code.
HERE MY UNITY PLAYLIST
👇🏽
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.
CHECK OUT THIS CRAZY EXPERIMENT
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.
Не удается добавить компонент скрипта, потому что класс скрипта не найден?
Вчера я обновил единство с единства 5 до 2018.2.2f1. Скрипты Unity не загружаются после обновления 2018.2.2f1.
Как только я пытаюсь воспроизвести сцену, сценарии не загружаются, и я не могу снова добавить сценарий, выдает эту ошибку:
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.
Если у вас все еще есть старая копия проекта, сначала обновите проект Unity до Unity 2017 , а затем до 2018.2.2f1 .
Вот несколько возможных причин, по которым вы можете получить эту ошибку (заказано с большой вероятностью)
1. Имя сценария не соответствует имени класса.
Если вызывается имя сценария MyClass , имя класса должно быть MyClass . Это также чувствительно к регистру. Дважды проверьте, чтобы убедиться, что это не проблема. Чтобы убедиться, что проблема не в этом, скопируйте имя класса и вставьте его в качестве имени скрипта, чтобы убедиться, что проблема не в этом.
Обратите внимание, что если у вас есть несколько классов в одном сценарии, имя класса, которое должно совпадать с именем сценария, — это класс, производный от MonoBehaviour .
2. В вашем скрипте ошибка. Поскольку это обновление, есть вероятность, что вы используете API, который сейчас устарел и удален. Откройте свой скрипт с помощью Visual Studio и посмотрите, есть ли там ошибка, а затем исправьте ее. Обычно под кодом имеется красная линия, указывающая на наличие ошибки.
3. Плохой импорт с помощью импортера Unity и его сценария автоматического обновления.
О. Первое, что нужно сделать, это перезапустить редактор Unity.
B. Щелкните правой кнопкой мыши вкладку «Проект», затем выберите «Повторно импортировать все».
C. Если проблема все еще существует, остается только удалить проблемный скрипт и создать новый. Есть более простой способ сделать это, если скрипт прикреплен ко многим игровым объектам в вашей сцене.
A. Откройте скрипт, скопируйте его содержимое в блокнот.
B. В редакторе и на вкладке « Проект » щелкните правой кнопкой мыши сценарий «CubeScript», выберите «Найти ссылки в сцене» .
C .Unity теперь будет отображать только те игровые объекты, к которым прикреплен этот скрипт. Удалите старый скрипт. Создайте новый, затем скопируйте содержимое из блокнота в этот новый скрипт. Теперь вы можете просто перетащить новый скрипт на все отфильтрованные игровые объекты в сцене. Сделайте это для каждого скрипта. Это ручная работа, но она должна исправить ваши проблемы после завершения.
Reproduction steps:
1. Create a new script.
2. Change the filename of that script.
3. Add script to an object in the scene.
Expected error message: «Can’t add script component ‘NewBehaviourScript’ because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match.»
Actual error message: «Can’t add script behaviour VisualContainerAsset. The script needs to derive from MonoBehaviour!»
Reproduced: 2018.1.0a5, 2018.1.0f1
Not reproducible: 2017.1.3p1, 2017.2.1p3, 2017.3.1f1, 2018.1.0a4, 2018.2.0b1
Cant add script component. Script Class cannot be found.
It’s a bit difficult to diagnose without seeing your code and directory structure of your Scripts folder, but I would start by double-checking that the script file and the class inside it are both named «RandomSoundPlayer» without any typos and that the class compiles without errors.
bryson thornton
bryson thornton
thanks. it worked
Tojo Alex
Tojo Alex
thanks i had same issue
Posting to the forum is only allowed for members with active accounts.
Please sign in or sign up to post.
$begingroup$
I’m a beginner in unity so I got this problem.
Here is the script:
using UnityEngine;
using System.Collections;
public class Playercontrol: MonoBehaviour {
public float maxspeed = 10f;
bool facingRight = true;
void FixedUpdate () {
float move = Input.GetAxis ("Horizontal");
GetComponent<Rigidbody2D>().velocity
= new Vector2(move * maxspeed, GetComponent<Rigidbody2D>().velocity.y);
if (move > 0 && !facingRight){
Flip ();
} else if (move < 0 && facingRight) {
Flip ();
}
}
void Flip() {
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
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.
House♦
72.9k16 gold badges180 silver badges270 bronze badges
asked Apr 25, 2015 at 15:30
$endgroup$
4
$begingroup$
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.
answered Apr 25, 2015 at 18:33
$endgroup$
2
$begingroup$
Old question, but I solved this problem using the Help menu and then Reset Packages to defaults.
answered Mar 4, 2021 at 18:45
TarodTarod
1116 bronze badges
$endgroup$
$begingroup$
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.
answered Apr 25, 2015 at 16:43
House♦House
72.9k16 gold badges180 silver badges270 bronze badges
$endgroup$
You must log in to answer this question.
Not the answer you’re looking for? Browse other questions tagged
.
Not the answer you’re looking for? Browse other questions tagged
.
Не могу добавлять скрипты.
Не могу добавлять скрипты.
Здравствуйте! Я недавно начал разбираться в Unity и столкнулся с проблемой. Когда я начинаю добавлять скрипты мне выдает ошибку:»Can’t add script: Can’t add script component ‘NewBehaviourScript’ becausethe script class cannot be found. Make sure that there are no compile errors and that the file name and class name match.»
Как я понял такое может возникать из-за разных имен класса в коде, и самого c# файла, но у меня абсолютно точно все совпадает! Помогите пожалуйста разобраться, ведь в интернете ничего подобного я не находил.
- Meerex
- UNец
- Сообщения: 47
- Зарегистрирован: 27 апр 2019, 18:44
Re: Не могу добавлять скрипты.
samana 27 апр 2019, 20:06
Сталкиваюсь с этим редко, но просто пересоздаю скрипт заново.
-
samana - Адепт
- Сообщения: 4733
- Зарегистрирован: 21 фев 2015, 13:00
- Откуда: Днепропетровск
Re: Не могу добавлять скрипты.
Meerex 27 апр 2019, 20:52
samana писал(а):Сталкиваюсь с этим редко, но просто пересоздаю скрипт заново.
Но у меня это происходит всегда! Как бы я его не называл или ещё что-то.
- Meerex
- UNец
- Сообщения: 47
- Зарегистрирован: 27 апр 2019, 18:44
Re: Не могу добавлять скрипты.
1max1 28 апр 2019, 01:33
Пример скрипта покажи. У тебя точно имя класса и файла совпадают? Может где-то русские буквы вместо английских есть.
-
1max1 - Адепт
- Сообщения: 5285
- Зарегистрирован: 28 июн 2017, 10:51
Re: Не могу добавлять скрипты.
seaman 28 апр 2019, 08:40
Класс в скрипте от MonBehaviour наследуется?
- seaman
- Адепт
- Сообщения: 8351
- Зарегистрирован: 24 янв 2011, 12:32
- Откуда: Самара
Re: Не могу добавлять скрипты.
Meerex 28 апр 2019, 11:19
1max1 писал(а):Пример скрипта покажи. У тебя точно имя класса и файла совпадают? Может где-то русские буквы вместо английских есть.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
точь в точь
- Meerex
- UNец
- Сообщения: 47
- Зарегистрирован: 27 апр 2019, 18:44
Re: Не могу добавлять скрипты.
Meerex 28 апр 2019, 11:20
seaman писал(а):Класс в скрипте от MonBehaviour наследуется?
Привел пример скрипта выше, наследуется.
- Meerex
- UNец
- Сообщения: 47
- Зарегистрирован: 27 апр 2019, 18:44
Re: Не могу добавлять скрипты.
Meerex 28 апр 2019, 11:33
То же самое происходит и тогда, когда я пытаюсь добавить Playables C# скрипты
- Meerex
- UNец
- Сообщения: 47
- Зарегистрирован: 27 апр 2019, 18:44
Re: Не могу добавлять скрипты.
seaman 28 апр 2019, 16:32
Запакуй папку с проектом и выложи куда-нибудь. Может разберемся.
- seaman
- Адепт
- Сообщения: 8351
- Зарегистрирован: 24 янв 2011, 12:32
- Откуда: Самара
Re: Не могу добавлять скрипты.
Meerex 28 апр 2019, 17:09
seaman писал(а):Запакуй папку с проектом и выложи куда-нибудь. Может разберемся.
Абсолютно любой проект реагирует так.
- Meerex
- UNец
- Сообщения: 47
- Зарегистрирован: 27 апр 2019, 18:44
Re: Не могу добавлять скрипты.
seaman 28 апр 2019, 18:24
Абсолютно любой и выложи.
Не факт, что кто -то, что-то найдет. Но вдруг.
- seaman
- Адепт
- Сообщения: 8351
- Зарегистрирован: 24 янв 2011, 12:32
- Откуда: Самара
Re: Не могу добавлять скрипты.
Кларити 09 ноя 2019, 15:23
Та же самая проблема, всё совпадает, должно работать, казалось бы, но реальность сильно расходится с ожиданиями.
- Кларити
- UNец
- Сообщения: 1
- Зарегистрирован: 09 ноя 2019, 15:19
Вернуться в Почемучка
Кто сейчас на конференции
Сейчас этот форум просматривают: waruiyume, Yandex [Bot] и гости: 24
2 / 1 / 1 Регистрация: 27.06.2019 Сообщений: 193 |
|
1 |
|
Не могу добавить на объект скрипт01.01.2020, 13:49. Показов 22253. Ответов 8
Ни на один объект не добавляется ни одни скрипт. Пробовал создать новый скрипт, не запуская его в visual studio, не помогло. Миниатюры
__________________
0 |
3088 / 1617 / 921 Регистрация: 26.10.2018 Сообщений: 4,620 |
|
01.01.2020, 15:00 |
2 |
Сначала исправь все ошибки в проекте и смотри чтобы имя скрипта совпадало с именем класса, ну и надеюсь он у тебя наследуется от монобеха.
1 |
2 / 1 / 1 Регистрация: 27.06.2019 Сообщений: 193 |
|
01.01.2020, 15:33 [ТС] |
3 |
1max1, имя скрипта совпадает с именем класса, так как даже присоединиться новых скриптов возникает эта ошибка. Ошибок в скрипте нет, по той же причине. Добавлено через 1 минуту
0 |
293 / 215 / 85 Регистрация: 17.02.2016 Сообщений: 1,269 Записей в блоге: 1 |
|
01.01.2020, 16:24 |
4 |
Сообщение было отмечено Max1219 как решение Решение в какихто скриптах ошибки
1 |
2 / 1 / 1 Регистрация: 27.06.2019 Сообщений: 193 |
|
01.01.2020, 16:33 [ТС] |
5 |
Steroid, то-есть из-за ошибки в одном скрипте не работает ни один?
0 |
293 / 215 / 85 Регистрация: 17.02.2016 Сообщений: 1,269 Записей в блоге: 1 |
|
01.01.2020, 16:42 |
6 |
то-есть из-за ошибки в одном скрипте не работает ни один ага
1 |
3088 / 1617 / 921 Регистрация: 26.10.2018 Сообщений: 4,620 |
|
01.01.2020, 18:51 |
7 |
В консоле же пишет все ошибки, смотри и исправляй.
0 |
1 / 1 / 1 Регистрация: 25.01.2020 Сообщений: 48 |
|
30.01.2020, 19:03 |
8 |
Пару лет назад столкнулся с такой же проблемой или очень похожей. Причина была в том что у меня была не одна папка со скриптами к одной игре и я делал скрипты с одинаковыми названиями. После чего, у меня скрипт не прикреплялся путём переноса, ни через строку поиска. Удалил скрипты с повторяющимися названиями (хоть и в разных папках) и проблема исчезла.
0 |
3088 / 1617 / 921 Регистрация: 26.10.2018 Сообщений: 4,620 |
|
30.01.2020, 19:16 |
9 |
Starkinc, название классов совпадало, и не важно в разных они папках или нет.
0 |