Ошибка cant add script как исправить

Introduction

In this arti­cle we look at the caus­es of the «Can’t Add Script» error in Uni­ty in order to under­stand why it occurs and iden­ti­fy what actions to take to fix it.

Dear read­er

In the chan­nel there lots of videos about Blender, Uni­ty and pro­gram­ming
in which we solve dif­fer­ent prob­lems and we pro­vide use­ful infor­ma­tion on these topics.

🍷🧐

In the fol­low­ing video you can see a brief descrip­tion 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 Uni­ty 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 com­po­nent to a GameOb­ject 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 exten­sion «.cs» does not match the name of the pro­gram­ming class that is defined inside it. This usu­al­ly hap­pens when we cre­ate a Script and then change the name of the file with­out doing a Refac­tor­ing process.

To solve this prob­lem first we must iden­ti­fy the Script that has con­flicts, this can be done with the infor­ma­tion pro­vid­ed by the «Can’t Add Script» error win­dow that appears when we try to add the Script with con­flicts to a GameOb­ject. If you do not remem­ber which Script pro­duced the error, you can cre­ate an Emp­ty GameOb­ject and start adding each of the Scripts until the error appears.

Once we know which is the Script that gen­er­ates the «Can’t Add Script» error, we open it and we locate the part of the class def­i­n­i­tion, which begins as follows:

pub­lic 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 mod­i­fy the name of the class to match the name of the file, or mod­i­fy the name of the file to match the name of the class.

Once this prob­lem is solved it will be pos­si­ble to add the Script to a GameOb­ject. If you need to rename the Script the best way is to right click on the «Name­OfThe­Class» name and then click on «Rename», this will make Uni­ty mod­i­fy that name in all the places where that Script is used.

MOST SEARCHED VIDEOS FROM MY CHANNEL

ABOUT UNITY

ABOUT BLENDER

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

The sec­ond rea­son why the «Can’t Add Script» error occurs in Uni­ty is when new Scripts are cre­at­ed while there are errors in con­sole, in gen­er­al these are syn­tax errors (errors in writ­ing the code). The rea­son in this case is that if there are errors in con­sole, Uni­ty can not com­pile, there­fore if we cre­ate a new Script at this point, even if the file has been cre­at­ed, the pro­gram­ming class can not be added to the engine, in oth­er words Uni­ty will not know that this Script exists until it compiles.

The solu­tion in this case is to solve all the errors in the con­sole, this will make Uni­ty com­pile and reg­is­ter the new Script. From that point on you will be able to assign the Script to a GameObject.

Когда вы пытаетесь добавить новый скрипт в свой проект Unity, иногда может возникнуть ошибка «Can’t add script». Это может быть вызвано несколькими причинами, но в большинстве случаев решение проблемы довольно простое.

Причины ошибки «Can’t add script»

1. Неправильная папка

Когда вы пытаетесь добавить скрипт, Unity создает новый файл в выбранной вами папке. Если эта папка корневая папка вашего проекта или какая-то другая системная папка, Unity не даст вам создать новый файл скрипта. Это связано с тем, что Unity не позволяет вам сохранять файлы ваших скриптов в системных папках.

2. Создание скрипта другой платформы

Если вы пытаетесь создать скрипт для платформы, на которой не работает Unity (например, для Mac, если вы работаете на ПК), это может вызвать ошибку «Can’t add script». В этом случае вам нужно создать скрипт на платформе, на которой вы работаете.

3. Проблемы с правами доступа

Если вы пытаетесь создать скрипт в защищенной папке, может возникнуть ошибка «Can’t add script». В этом случае вам нужно убедиться, что вы имеете достаточные права на запись в этой папке.

Как исправить ошибку «Can’t add script»

Существует несколько способов, которым вы можете исправить ошибку «Can’t add script»:

1. Проверьте папку

Перед тем, как создать новый скрипт, убедитесь, что вы выбрали правильную папку для сохранения файла. Не сохраняйте скрипты в системных или защищенных папках.

2. Создайте скрипт на правильной платформе

Убедитесь, что вы создаете скрипт на платформе, на которой вы работаете.

3. Измените права доступа

Если вы не можете создать скрипт из-за проблем с правами доступа, измените права доступа к папке, в которой вы хотите сохранить свой скрипт.

Выводы

Ошибка «Can’t add script» может быть вызвана неправильной папкой, созданием скрипта для другой платформы или проблемами с правами доступа. Однако, при условии правильной работы вашего проекта, проблема обычно может быть легко решена с помощью простых действий.

Не удается добавить компонент скрипта, потому что класс скрипта не найден?

Вчера я обновил единство с единства 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.

Introduction

In this arti­cle we look at the caus­es of the «Can’t Add Script» error in Uni­ty in order to under­stand why it occurs and iden­ti­fy what actions to take to fix it.

In the fol­low­ing video you can see a brief descrip­tion 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 Uni­ty through code.

HERE MY UNITY PLAYLIST
👇🏽

We are almost 700 devs in the new channel. Subscribe here!❤️

Why do the «Can’t Add Script» Error occur in Unity?

This error in which we are not allowed to add a Script or com­po­nent to a GameOb­ject 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 exten­sion «.cs» does not match the name of the pro­gram­ming class that is defined inside it. This usu­al­ly hap­pens when we cre­ate a Script and then change the name of the file with­out doing a Refac­tor­ing process.

To solve this prob­lem first we must iden­ti­fy the Script that has con­flicts, this can be done with the infor­ma­tion pro­vid­ed by the «Can’t Add Script» error win­dow that appears when we try to add the Script with con­flicts to a GameOb­ject. If you do not remem­ber which Script pro­duced the error, you can cre­ate an Emp­ty GameOb­ject and start adding each of the Scripts until the error appears.

Once we know which is the Script that gen­er­ates the «Can’t Add Script» error, we open it and we locate the part of the class def­i­n­i­tion, which begins as follows:

pub­lic 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 mod­i­fy the name of the class to match the name of the file, or mod­i­fy the name of the file to match the name of the class.

Once this prob­lem is solved it will be pos­si­ble to add the Script to a GameOb­ject. If you need to rename the Script the best way is to right click on the «Name­OfThe­Class» name and then click on «Rename», this will make Uni­ty mod­i­fy 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 sec­ond rea­son why the «Can’t Add Script» error occurs in Uni­ty is when new Scripts are cre­at­ed while there are errors in con­sole, in gen­er­al these are syn­tax errors (errors in writ­ing the code). The rea­son in this case is that if there are errors in con­sole, Uni­ty can not com­pile, there­fore if we cre­ate a new Script at this point, even if the file has been cre­at­ed, the pro­gram­ming class can not be added to the engine, in oth­er words Uni­ty will not know that this Script exists until it compiles.

The solu­tion in this case is to solve all the errors in the con­sole, this will make Uni­ty com­pile and reg­is­ter the new Script. From that point on you will be able to assign the Script to a GameObject.

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.

Things to try:

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.

Не могу добавлять скрипты.

Не могу добавлять скрипты.

Здравствуйте! Я недавно начал разбираться в 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
Адепт
 
Сообщения: 5281
Зарегистрирован: 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


Вернуться в Почемучка

Кто сейчас на конференции

Сейчас этот форум просматривают: Yandex [Bot] и гости: 28

$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's user avatar

House

72.9k16 gold badges180 silver badges270 bronze badges

asked Apr 25, 2015 at 15:30

Bob's user avatar

$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

Mason Dixon Ormous's user avatar

$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

Tarod's user avatar

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's user avatar

HouseHouse

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

.

Привет, ребята! Нужна ваша помощь! Проходил урок . В общем, юнити никак не хочет съедать скрипт, который представлен в этом уроке(или ниже). В чем может быть проблема? Ошибка: cant add component because it doesnt exist.
А вот сам скрипт:

using UnityEngine;
using System.Collections;

public class characterController : MonoBehaviour {
public float maxSpeed = 10f;
public float jumpForce = 700f;
bool facingRight = true;
bool grounded = false;
public Transform groundCheck;
public float groundRadius = 0.2f;
public LayerMask whatIsGround;

public float move;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void FixedUpdate () {

grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);

move = Input.GetAxis («Horizontal»);

}

void Update(){
if (grounded && (Input.GetKeyDown (KeyCode.W)||Input.GetKeyDown (KeyCode.UpArrow))) {

rigidbody2D.AddForce (new Vector2(0f,jumpForce));
}
rigidbody2D.velocity = new Vector2 (move * maxSpeed, rigidbody2D.velocity.y);

if (move > 0 && !facingRight)
Flip ();
else if (move < 0 && facingRight)
Flip ();

if (Input.GetKey(KeyCode.Escape))
{
Application.Quit();
}

if (Input.GetKey(KeyCode.R))
{
Application.LoadLevel(Application.loadedLevel);
}

}

void Flip(){
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}

[Unity3d] Как исправить: невозможно добавить компонент скрипта, потому что не удается найти класс скрипта

Вчера обновил unity с unity5 до 2018.2.2f1. Скрипты Unity не загружаются после обновления 2018.2.2f1.

Как только я пытаюсь воспроизвести сцену, сценарии не загружаются, и я не могу добавить сценарий снова, он дает следующую ошибку:

Невозможно добавить компонент скрипта CubeScript, потому что класс скрипта не найден. Убедитесь, что нет ошибок компиляции и что имя файла и имя класса совпадают.

  • 2 unity5 до 2018.2.2f1 — большой скачок. Лучше было бы выполнить unity5 до 2017, а не 2018.2.2f1, чтобы уменьшить вероятность возникновения проблем в обновленном проекте. Где находится «CubeScript» в вашем проекте?
  • @Programmer Это у меня в активах в папке _scripts и я открыл его из ассетов, и скрипт открывается как обычно в monodevelop.
  • Есть флудер Packages следующий на Assets я должен что-то с этим делать? @Программист
  • Это совершенно не профессионально, я хочу другое решение
  • Мой проект настолько велик, что я не могу зайти в каждую папку и сделать это вручную, есть ли что-нибудь лучше, чем это

Если у вас все еще есть старая копия проекта, обновите проект Unity до Единство 2017 сначала потом 2018.2.2f1.

Вот несколько возможных причин, по которым вы можете получить эту ошибку (очень вероятно, заказано)

1Имя .Script не соответствует имени класса.

Если имя скрипта называется MyClass, имя класса должно быть MyClass. Это также чувствительно к регистру. Дважды проверьте, чтобы убедиться, что проблема не в этом. Чтобы убедиться, что проблема не в этом, скопируйте имя класса и вставьте его в качестве имени сценария, чтобы убедиться, что проблема не в этом.

Обратите внимание: если у вас есть несколько классов в одном скрипте, имя класса, которое должно совпадать с именем скрипта, — это класс, производный от MonoBehaviour.


2.В вашем скрипте есть ошибка. Поскольку это обновление, есть вероятность, что вы используете API, который устарел и удален. Откройте свой скрипт в Visual Studio и посмотрите, есть ли там ошибка, а затем исправьте ее. Обычно под кодом есть красная линия, указывающая на ошибку.


3.Плохой импорт с импортером Unity и его скриптом автоматического обновления.

Что стоит попробовать:

А. Первое, что нужно сделать, это перезапустить редактор Unity.

B.Щелкните правой кнопкой мыши вкладку Project, затем щелкните «Импортировать все заново»

C.Если проблема не исчезла, остается только удалить проблемный сценарий и создать новый. Есть более простой способ сделать это, если скрипт прикреплен ко многим GameObject в вашей сцене.

А. Откройте скрипт, скопируйте его содержимое в блокнот.

B.Из редактора и на Проект на вкладке правой кнопкой мыши щелкните скрипт «CubeScript», выберите «Найти ссылки в сцене».

C.Unity теперь будет показывать только все GameObject, к которым прикреплен этот скрипт. Удалите старый скрипт. Создайте новый, затем скопируйте содержимое из блокнота в этот новый скрипт. Теперь вы можете просто перетащить новый скрипт на все отфильтрованные GameObject в сцене. Сделайте это для каждого задействованного сценария. Это ручная работа, но по завершении она должна решить ваши проблемы.

  • Я ценю ваш ответ, но общедоступные типы данных, используемые в FPSController все пропало, и другие сценарии также сбросили данные, которые я ввел в окне инспектора редактора единства.
  • 1 Если №3 — ваше последнее средство, вам придется сделать это вручную. Если у вас нет старого проекта, вы действительно ничего не можете сделать, кроме как воссоздать и переназначить их самостоятельно. Я знаю, что это отстой, но я всегда говорю людям выполнять инициализацию переменных через скрипт, и вот почему. Иногда сцена может сходить с ума из-за обновления или сбоя.Если инициализация, такая как переменные и присоединение скрипта, выполняется через скрипт, все, что вам нужно сделать, это перетащить скрипт в другую папку, а затем перетащить его обратно.
  • 1 Бывает. Для этого вам даже не нужно обновлять Unity. Думаю, вам следует последовать моему совету и начать прикреплять скрипты из скриптов. Это сэкономит вам время, и вы не столкнетесь с той же проблемой в будущем. Всегда делайте копию проекта перед его обновлением. Это обязательно.
  • 2 @ В замешательстве Да. Вместо того, чтобы перетаскивать скрипт на GameObject, что проще. вы должны создать сценарий с именем ComponentInit который прикреплен к пустому проекту. Этот скрипт вы должны использовать для поиска GameObjects, а затем прикрепить к ним необходимые скрипты. Это верно, особенно когда у вас большой проект. Например, GameObject shipObj = GameObject.Find('Ship').AddComponent();.
  • 1 О, спасибо, это важно, я впервые вижу .AddComponent Это было бы очень удобно.

Публикация здесь в исторических целях, и если кто-то из Google окажется здесь, у меня была точно такая же проблема (я на Windows 10), и вот как я ее исправил:

  • Если вы нажмете на Консоль, вы должны увидеть пустую ошибку. Не волнуйтесь, это ошибка редактора, и вы можете увидеть журнал редактора, выбрав раскрывающееся окно консоли и выбрав Открыть журнал редактора.

Для меня проблема заключалась в том, что не удалось найти «Tools Roslyn csc», что Unity использует для компиляции файлов C #.

  • я открыл C:Program FilesUnityHubEditor2019.2.14f1EditorDataToolsRoslynScriptsunity_csc.bat и я добавил «.exe» в строку '%APPLICATION_CONTENTS%ToolsRoslyncsc' /shared %*

(Теперь эта строка должна быть: '%APPLICATION_CONTENTS%ToolsRoslyncsc.exe' /shared %*)

Теперь работает отлично.

  • Это опасно?
  • Этого не должно быть, он только перенаправляет Unity на правильный исполняемый файл для использования, не о чем беспокоиться.

Еще одна вещь, которая может помочь помимо других ответов

  • Сделайте класс, который наследует от MonoBehaviour, первым классом в файле. Это устранило эту проблему для меня.

Проверка ошибок консоли и их исправление — хороший способ решить проблемы «Не удается добавить компонент сценария, потому что класс сценария не найден?», Хотя ошибка кажется несущественной. У меня это работает, когда я исправляю ошибку в другом скрипте.

для меня я обнаружил, что это был скрипт, который я не использовал, который был связан с плеером и другими скриптами, которые я удалил.

Tweet

Share

Link

Plus

Send

Send

Pin

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.

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.

Error

Programmer's user avatar

Joe's user avatar

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.

How to solve «Can’t Add Script» in Unity

In this arti­cle we look at the caus­es of the «Can’t Add Script» error in Uni­ty in order to under­stand why it occurs and iden­ti­fy what actions to take to fix it.

Dear read­er

In the chan­nel there lots of videos about Blender, Uni­ty and pro­gram­ming
in which we solve dif­fer­ent prob­lems and we pro­vide use­ful infor­ma­tion on these topics.

In the fol­low­ing video you can see a brief descrip­tion 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 Uni­ty 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 com­po­nent to a GameOb­ject 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 exten­sion «.cs» does not match the name of the pro­gram­ming class that is defined inside it. This usu­al­ly hap­pens when we cre­ate a Script and then change the name of the file with­out doing a Refac­tor­ing process.

To solve this prob­lem first we must iden­ti­fy the Script that has con­flicts, this can be done with the infor­ma­tion pro­vid­ed by the «Can’t Add Script» error win­dow that appears when we try to add the Script with con­flicts to a GameOb­ject. If you do not remem­ber which Script pro­duced the error, you can cre­ate an Emp­ty GameOb­ject and start adding each of the Scripts until the error appears.

Once we know which is the Script that gen­er­ates the «Can’t Add Script» error, we open it and we locate the part of the class def­i­n­i­tion, which begins as follows:

pub­lic 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 mod­i­fy the name of the class to match the name of the file, or mod­i­fy the name of the file to match the name of the class.

Once this prob­lem is solved it will be pos­si­ble to add the Script to a GameOb­ject. If you need to rename the Script the best way is to right click on the «Name­OfThe­Class» name and then click on «Rename», this will make Uni­ty mod­i­fy that name in all the places where that Script is used.

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.

House's user avatar

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.

House's user avatar

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.3.11.43304

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

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.

Things to try:

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.

  • Ошибка cant add audio вконтакте
  • Ошибка canon загрузите бумагу ltr
  • Ошибка canon pixma ip1500 печатающая головка не установлена методы борьбы
  • Ошибка canon pixma e15
  • Ошибка canon mg3540 b200