Ошибка юнити cant add script component

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.

Здесь несколько вариантов причины ошибки:

1)
Вы создали скрипт, добавили его как компонент, но случайно удалили скрипт впоследствии (маловероятно, но все же)

2)
проверьте, объявили ли в самом скрипте класс. Если вы пишете на C#, то вот структура скрипта:

using System.Collections; 
using System.Collections.Generic;
using UnityEngine;

public class /*название скрипта */ : MonoBehaviour {

         void Start () {

        }
       
        void Update () {
        }
}

[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

Programmers can’t add script component because the script class cannot be found, which obliterates your programming experience in Visual Studio. Consequently, your system or application launches the Unity add monobehaviour to gameobject error that prevents the elements from rendering the processes.Cant Add Script Component in Your Program

In addition, although the error affects no monobehaviour scripts in the file, it can cause unexpected mistakes when compiling complex files, but fortunately, we are here to help. Namely, this profound guide recreates the invalid exception, uses real-life examples, and teaches developers how to add script component in Unity.

Contents

  • Why You Can’t Add Script Component in Your Program?
    • – Importing a Script to the Character
    • – Connecting the Database to Unity 2D
  • Fix the Script Component Bug That Messes up the Script Class
    • – Changing a Code Line in the Unity Script
  • Conclusion

Why You Can’t Add Script Component in Your Program?

You can’t add script behaviour because the script needs to derive from monobehaviour, which can affect the project’s old copy or files. Furthermore, this minor mistake ruins other commands and functions. As a result, developers and programmers cannot complete the project because the associated script cannot be loaded.

Furthermore, users sometimes can t add component because class spherecollider doesn t exist, an error caused by a few elements. Therefore, we will show you a few scripts that recreate the mistake using standard features and tags, confirming our theory it can appear in simple and complex projects.

For example, although we can’t add script behaviour callbackexecutor and recreate the identical mistake, the culprit remains unchanged no matter how different the values are. Hence, you should stay calm if your document or application has other properties because the debugging principles will work for all.

However, we will wait to provide the solutions because we must learn the initial debugging step and why Unity can’t add script the script don’t inherit. Namely, we will first recreate and provide the incorrect inputs, which is part of the troubleshooting operations for a better understanding.

After that, developers can scan and compare the example with their files to pinpoint the exact cause and apply the solutions. But first, we suggest double-checking your elements for obvious mistakes because no one is perfect, especially when creating complex files with many advanced processes.

– Importing a Script to the Character

The first instance imports a script to the character, but unfortunately, this syntax is incorrect and throws the class error in your system. Although the name matches the behavior, the mistake that halts further code alterations appears.

The following example provides the complete document:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

[RequireComponent(typeof(CharacterController))]

public class SC_FPSController : MonoBehaviour

{

public float walkingSpeed = 7.5f;

public float runningSpeed = 11.5f;

public float jumpSpeed = 8.0f;

public float gravity = 20.0f;

public Camera playerCamera;

public float lookSpeed = 2.0f;

public float lookXLimit = 45.0f;

CharacterController characterController;

Vector3 moveDirection = Vector3.zero;

float rotationX = 0;

[HideInInspector]

public bool canMove = true;

void Start()

{

characterController = GetComponent<CharacterController>();

Cursor.lockState = CursorLockMode.Locked;

Cursor.visible = false;

}

void Update()

{

Vector3 forward = transform.TransformDirection(Vector3.forward);

Vector3 right = transform.TransformDirection(Vector3.right);

bool isRunning = Input.GetKey(KeyCode.LeftShift);

float curSpeedX = canMove ? (isRunning ? runningSpeed : walkingSpeed) * Input.GetAxis(“Vertical”) : 0;

float curSpeedY = canMove ? (isRunning ? runningSpeed : walkingSpeed) * Input.GetAxis(“Horizontal”) : 0;

float movementDirectionY = moveDirection.y;

moveDirection = (forward * curSpeedX) + (right * curSpeedY);

if (Input.GetButton(“Jump”) && canMove && characterController.isGrounded)

{

moveDirection.y = jumpSpeed;

}

else

{

moveDirection.y = movementDirectionY;

}

if (!characterController.isGrounded)

{

moveDirection.y -= gravity * Time.deltaTime;

}

characterController.Move(moveDirection * Time.deltaTime);

if (canMove)

{

rotationX += -Input.GetAxis(“Mouse Y”) * lookSpeed;

rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);

playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);

transform.rotation *= Quaternion.Euler(0, Input.GetAxis(“Mouse X”) * lookSpeed, 0);

}

}

}

The code snippet confirms the system can launch the error when you expect the least. Therefore, predicting it is almost impossible.

– Connecting the Database to Unity 2D

Programmers can experience class mistakes when connecting the database to Unity 2D using standard elements and properties. For instance, we will show you an example with fewer functions than the previous chapter script that launches an exact error and obliterates your old project files.Cant Add Script Component in Your Program Causes

Namely, you will experience the bug as soon as you attempt to assign a script for the button that sends the user input. Furthermore, you can compare the public connections to your document to pinpoint the exact culprit.

The following example provides more information about the script:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using Mono.Data.Sqlite;

using System.Data;

using System;

public class Connection : MonoBehaviour

{

public SqliteConnection dbconnection;

public string path;

public void setConnection()

{

path = Application.dataPath + “/basa/ mybd.bytes”;

dbconnection = new SqliteConnection (“URI-file” + path);

dbconnection.Open();

if (dbconnection.State == ConnectionState.Open)

{

SqliteCommand cmd = new SqliteCommand();

cmd.Connection = dbconnection;

cmd.CommandText = “SELECT * FROM Items”;

SqliteDataReader r = cmd.ExecuteReader();

while (r.Read())

Debug.Log (String.Format (“{0} {1}”, r[0], r[1]));

}

}

}

This arbitrary example discourages programmers and developers because they believe the elements and fully functional and will not cause any bugs. But, unfortunately, they will soon realize the script and class’s names do not match, forcing their systems to display the full invalid exception that blocks your project.

In addition, the error can persist even if users change the names and match the locations, which needs to be clarified. Luckily, the debugging methods only take a few minutes, and you can apply them to any document or script.

Fix the Script Component Bug That Messes up the Script Class

You can match the script and class names to quickly fix the script from your applications without causing further complications. In addition, we suggest updating the Unity project to the latest version because it supports all modern commands and functions, which is vital when compiling complex projects with many options.

So, we confirmed the error’s most standard culprits, such as non-matching names, bugs due to outdated versions, and bad imports for the Unity scripts.

However, we must now provide the debugging principles that clear the script and prevent the mistake from happening again, especially in similar projects. Luckily, this article’s first solution teaches you how to reimport the code snippets using standard commands.

You can learn about this solution in the following example:

  • Restart the Unity Editor to remove any inconsistencies.
  • Right-click the project tab and select the “Reimport All” property
  • If the mistake still exists, you must delete the incorrect script and create a new one.

Fortunately, there is a more accessible alternative to this approach, as explained in the following bullet list:

  • Open the Unity script and copy the contents into a notepad.
  • Right-click the “CubeScript” from the Editor and project tab, and select “Find References In Scene”.
  • The program will display the objects attached to the script. Delete the old script, create a new one, and copy the contents from the notepad. You can now drag the document to the filtered object in the scene.

Although this can be time-consuming, developers must repeat the solution for every affected script. It ensures the error will no longer appear.

– Changing a Code Line in the Unity Script

The second solution teaches developers to change a single code line in the Unity script to remove the mistake. Namely, several professional programmers confirmed this is an editor log bug that happens when you select the window dropdown menu.Changing a Code Line in the Unity Script

For instance, the error appears due to Unity’s incorrect location to compile C# files. In addition, the mistake affects Windows 10 or older versions.

Read the following example for more information:

C:Program FilesUnityHubEditor2022.2.14f1EditorDataToolsRoslynScriptsunity_csc.bat

This is the exact location programmers must open inside the system. In addition, they must add a single execution command to the application contest, as explained below:

%APPLICATION_CONTENTS%ToolsRoslyncsc.exe” /shared %*

This will debug the script without affecting other commands, although you must repeat the process for all incorrect commands and functions. Fortunately, the code exception indicates which commands fail so that you can quickly locate and apply the solution.

Conclusion

Programmers experience the script behavior error that needs to derive from mono behavior when their project has names that do not match. Fortunately, we covered all critical points that help you remove the mistake summarized in the following list:

  • This is a standard Unity script bug that prevents further code operations
  • Recreating the error is the primary troubleshooting and debugging step
  • You can try to debug the script by matching the names, but it does not guarantee the mistake will disappear
  • We suggest updating the latest Unity version to render all modern functions

Developing complex commands and functions is always challenging because programmers introduce many elements and properties. After reading this step-by-step guide, debugging the script class mistake should be easy.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

$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

73k17 gold badges183 silver badges271 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

73k17 gold badges183 silver badges271 bronze badges

$endgroup$

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

  • Ошибка юнити all compiler errors have to be fixed before you can enter playmode
  • Ошибка юнити 2019 тарков
  • Ошибка юнити 2018 4 28f1
  • Ошибка юнита zabbix server service
  • Ошибка юнита smbd service