The referenced script on this behaviour game object main camera is missing как исправить

Sometimes when I start my game, I get pointless warnings. I do not know where they come from and I do not have any objects that address a script that does not exist. How can I remove or fix these messages?

Console:

Inspector:

When I right click on the icon of the file in the inspector I get two possible options. Both of them do not work or when I try to click on them nothing happens.

Inspector context menu:

asked Mar 3, 2019 at 14:40

Timisorean's user avatar

TimisoreanTimisorean

1,3686 gold badges19 silver badges30 bronze badges

3

It happens when the file and the name class has not the same name.

Example:

  • The file is named SingleCube.cs
  • The class definition is public class Cube : MonoBehaviour

In this case, Unity is not able to link the file and the class. Both have to have the same name.

  • The file should be SingleCube.cs
  • And the class definition public class SingleCube : MonoBehaviour

answered Feb 29, 2020 at 11:08

Sergio Lema's user avatar

Sergio LemaSergio Lema

1,4411 gold badge14 silver badges25 bronze badges

2

The Editor script on the below page from Gigadrill Games did the job for me. Many thanks to them for creating this — missing scripts is a regular problem I have with my Unity workflow.

Just create an Editor folder anywhere in your project hierarchy (e.g. Plugins/Find Missing Scripts/Editor) and extract the script file in the RAR file linked in the below article.

You’ll have an option on your ‘Window’ menu in Unity to track down those pesky missing script components.

Finding Missing Scripts in Unity

Code also reproduced below:

using UnityEditor;
using UnityEngine;

namespace AndroidUltimatePlugin.Helpers.Editor
{
    public class FindMissingScriptsRecursively : EditorWindow
    {
        static int _goCount = 0, _componentsCount = 0, _missingCount = 0;

        [MenuItem("Window/FindMissingScriptsRecursively")]
        public static void ShowWindow()
        {
            GetWindow(typeof(FindMissingScriptsRecursively));
        }

        public void OnGUI()
        {
            if (GUILayout.Button("Find Missing Scripts in selected GameObjects"))
            {
                FindInSelected();
            }

            if (GUILayout.Button("Find Missing Scripts"))
            {
                FindAll();
            }
            EditorGUILayout.BeginHorizontal();
            {
                EditorGUILayout.LabelField("Component Scanned:");
                EditorGUILayout.LabelField("" + (_componentsCount == -1 ? "---" : _componentsCount.ToString()));
            }
            EditorGUILayout.EndHorizontal();
            
            EditorGUILayout.BeginHorizontal();
            {
                EditorGUILayout.LabelField("Object Scanned:");
                EditorGUILayout.LabelField("" + (_goCount == -1 ? "---" : _goCount.ToString()));
            }
            EditorGUILayout.EndHorizontal();
            
            EditorGUILayout.BeginHorizontal();
            {
                EditorGUILayout.LabelField("Possible Missing Scripts:");
                EditorGUILayout.LabelField("" + (_missingCount == -1 ? "---" : _missingCount.ToString()));
            }
            EditorGUILayout.EndHorizontal();
        }

        private static void FindAll()
        {
            _componentsCount = 0;
            _goCount = 0;
            _missingCount = 0;
            
            string[] assetsPaths = AssetDatabase.GetAllAssetPaths();

            foreach (string assetPath in assetsPaths)
            {
                Object[] data = LoadAllAssetsAtPath(assetPath);
                foreach (Object o in data)
                {
                    if (o != null)
                    {
                        if (o is GameObject)
                        {
                            FindInGO((GameObject) o);
                        }
                    }
                }
            }
            
            Debug.Log($"Searched {_goCount} GameObjects, {_componentsCount} components, found {_missingCount} missing");
        }

        public static Object[] LoadAllAssetsAtPath(string assetPath)
        {
            return typeof(SceneAsset).Equals(AssetDatabase.GetMainAssetTypeAtPath(assetPath))
                ?
                // prevent error "Do not use readobjectthreaded on scene objects!"
                new[] {AssetDatabase.LoadMainAssetAtPath(assetPath)}
                : AssetDatabase.LoadAllAssetsAtPath(assetPath);
        }

        private static void FindInSelected()
        {
            GameObject[] go = Selection.gameObjects;
            _goCount = 0;
            _componentsCount = 0;
            _missingCount = 0;
            foreach (GameObject g in go)
            {

                FindInGO(g);
            }

            Debug.Log($"Searched {_goCount} GameObjects, {_componentsCount} components, found {_missingCount} missing");
        }

        private static void FindInGO(GameObject g)
        {
            _goCount++;
            Component[] components = g.GetComponents<Component>();
            for (int i = 0; i < components.Length; i++)
            {
                _componentsCount++;
                if (components[i] == null)
                {
                    _missingCount++;
                    string s = g.name;
                    Transform t = g.transform;
                    while (t.parent != null)
                    {
                        var parent = t.parent;
                        s = parent.name + "/" + s;
                        t = parent;
                    }

                    Debug.Log(s + " has an empty script attached in position: " + i, g);
                }
            }

            // Now recurse through each child GO (if there are any):
            foreach (Transform childT in g.transform)
            {
                //Debug.Log("Searching " + childT.name  + " " );
                FindInGO(childT.gameObject);
            }
        }
    }
}

answered Aug 13, 2021 at 13:48

Christh's user avatar

ChristhChristh

5174 silver badges9 bronze badges

0

In my case the problem was a reference to a Component that had been deleted, inside a prefab file which was overridden by a variant which did not include the Component. So when I instantiated the variant, the missing component was briefly referenced as it was removed, causing this generic warning with no useful identifying data. I found it by:

  • restoring all recently deleted components one at a time until the error stopped

  • copying the guid from that component’s .meta file.

  • doing a raw text search for the guid in all *.prefab files (also *.scene and *.asset)

This requires Project Settings > Editor > Asset Serialization > Mode = Force Text.

answered May 28, 2021 at 17:42

Sarah Northway's user avatar

Sarah NorthwaySarah Northway

1,0091 gold badge14 silver badges23 bronze badges

1

I had this same issue as well. I think it’s caused by deleting the default scene but not changing the «Scenes in Build» in the build settings. Here’s how I fixed it.

  1. Go to your build settings (File > Build Settings). There should a greyed out box that says «deleted». This is the (now missing) default scene.
  2. Right click on it and remove it
  3. Add your current scene

Dharman's user avatar

Dharman

30.3k22 gold badges84 silver badges132 bronze badges

answered Jul 13, 2020 at 10:16

Idyia's user avatar

IdyiaIdyia

511 silver badge3 bronze badges

That happens when you’ve changed the C# class name of a script, or you changed the script’s file name in the project, so that they don’t match. In your case, the problem is with whichever script you have highlighted in your Inspector screenshot.

answered Mar 3, 2019 at 14:47

Ben Rubin's user avatar

Ben RubinBen Rubin

6,8157 gold badges33 silver badges80 bronze badges

7

You can remove this un-reachable script from inspector panel and load again as a component. So you can use your script with no problem agin.

answered Mar 3, 2019 at 15:02

silkworm's user avatar

silkwormsilkworm

531 silver badge9 bronze badges

1

If, or when, you first start your project — you move and/or rename the original default scene that was included in the «scenes» folder, Unity will throw an ever-increasing number of these false references until you end up sitting in the park throwing breadcrumbs at yourself. They can get into the thousands.

Here’s how to fix it:

  1. Go into «File -> Build Settings» and delete all the «Scenes in
    Build» then exit out of that window.
  2. Find that original renamed scene, double click it so it is
    active, and go to «File -> Save As…»
  3. Save this scene as a brand new scene with a new name. This is crucial. Don’t simply overwrite the file that is there. For instance, if the current
    file is named «scene_battlefield», rename it to something like
    «scene_battlefield_whatever».
  4. Delete the new file («scene_battlefield_whatever») by right-clicking
    on it in the «Assets» panel. However, you’ll notice that the name
    at the top of the screen still says «scene_battlefield_whatever».
  5. Go back to «File -> Save As…» again and this time click on the
    original file you had prior to renaming and overwrite it. The name
    at the top of the screen will change as expected (to
    «scene_battlefield»).
  6. Go back to «File -> Build Settings», add «scene_battlefield» (or
    whatever it’s called), and build the program to a folder. After the
    build is complete, you can delete the build. This built version of your program is unimportant.
  7. Restart Unity and load up the project as usual.

Basically the «Save As…» rewrites over all the old legacy script connections.

If you can’t remember which scene in your game is the original renamed scene, you’ll need to redo the «Save As…» part for each scene. However, you only have to do the «Build Settings» once.

And that’s it. You should never have these random scripts popping up again. Hope that helps.

answered Oct 4, 2019 at 2:08

Peter LeCirc's user avatar

This usually shows up when you assign a script to an object and then delete the script from your project. If you’re sure that no object in your scene has this script assigned, perhaps some object that gets instantiated at the run time does? Also, check out this page, it might help you find the source of these errors.

answered Mar 3, 2019 at 14:48

QmlnR2F5's user avatar

QmlnR2F5QmlnR2F5

87410 silver badges17 bronze badges

1

File name and public class name should be same like Test.cs so public class should be public class Test

enter image description here

Chuck D's user avatar

Chuck D

1,6182 gold badges16 silver badges32 bronze badges

answered Mar 11, 2021 at 15:39

Bimol Das's user avatar

In my case I had used Window->Rendering->Lighting->»Generate Lighting» on a Scene….»Scene1″ for example. Unity3d then created a Scene1 folder inside my Scenes directory parallel to my Scene1 asset.

I later renamed Scene1 to Level1, but the directory Scene1 did not change accordingly. I got these errors until I renamed the lighting folder to Level1 as well.

answered Jun 29, 2021 at 14:04

Brian Alan Carlson's user avatar

First click «Add Component» in the Editor.
Add the script named «NameFinder». Open your IDE (Rider, Visual Studio etc.). Fill the class with following lines.

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

public class NameFinder : MonoBehaviour
{
    // Update is called once per frame
    void Update()
    {
        Debug.Log("Name of the object is:" + gameObject.name);
    }
}

Come back to Unity and watch console while in Play mode. Name of your object should be printed each frame. If you can find it in the scene, good. Get out of the play mode and delete it.

If you can not find it in your scene, your scene file is corrupted. Close unity, open your scene file in a text editor, search for the name of your object and delete the object manually.

You may want to see how Unity stores scene objects. In my case I had to search for GUID and delete the stuff that has the same reference. (Transform and other components should be removed.)

answered Oct 22, 2022 at 18:06

Onat Korucu's user avatar

Onat KorucuOnat Korucu

94211 silver badges13 bronze badges

Actually, for me it is when I forget to end the game and then start editing the script!

When I save my script and go back into Unity I get this error.

Of course if I remember to end my game before editing this error doesn’t pop up.

answered Nov 28, 2022 at 17:37

Flashheart's user avatar

In my case this was not due to a missing script in the scene, but inside a Prefab that the scene uses.

Thanks to a post in Unity Forums.

answered Nov 30, 2022 at 21:07

GRASBOCK's user avatar

GRASBOCKGRASBOCK

6126 silver badges16 bronze badges

Hi,

I know, there is always a lot of questions about this error BUT I didn’t succeed to fix it with the previous answers…

So, please, let me explain.

I’m working with the Hololens tech. Recently, I have updated from HoloToolKit to MRTK V2 (new SDK provided by Microsoft and the community). My app worked with HoloToolKit, Unity and 2017.4. I updated for MRTKv2 and 2019.2 (recommended).

I have some scripts that use the camera position. In my previous app, Camera was BiCamera (GameObject), child of Basic (GameObject). And my BiCamera was tagged as MainCamera. Right now, my camera was Main Camera (with a space between the 2 words), tagged MainCamera, child of MixedRealityPlayspace. This camera is provided by the MRTKv2. I can’t change the settings.

So, when I’m in a Play mode I have this message in yellow :

 The referenced script on this Behaviour (Game Object 'Main Camera') is missing!

And when I move my Main Camera in order to simulate a walk of the user (Hololens = augmented reality), I have this message in red :

 NullReferenceException: Object reference not set to an instance of an object
 TextSpeedUI.Update () (at Assets/Scripts/TextSpeedUI.cs:23) 

I think the second message is linked to the first… My script TextSpeedUI needs the camera.transform to calculate walking speed (in fact not directly, he finds the public variable from another GameObject, but this GameObject requires Camera.transform).

TextSpeedUI.cs 23

 if (sd.isActiveAndEnabled && sd.Steps.Count > 4)
 {
     xzSpeed = (sd.Steps[sd.Steps.Count - 1].localMinPosition - sd.Steps[sd.Steps.Count - 4].localMinPosition) / ((sd.Steps[sd.Steps.Count - 1].t - sd.Steps[sd.Steps.Count - 4].t));

     txt.text = (xzSpeed.magnitude * 3.6).ToString("0.##"); // speed in km/h
 }

sd comes from public StepDetector sd; which is at the beginning of my script TextSpeedUI.cs

And my script StepDetector.cs calls public DataManager dm;

In my DataManager.cs script, I call at the beginning :

 public Camera Cam { get; private set; }

And in void Start :

 Cam = Camera.main;

I hope I’m clear… I think it’s an error in the name or other small error, but I don’t understand…

Thank for your help.

  

If you're a Unity developer, you might have come across the dreaded "Referenced Script on This Behaviour is Missing" error. This comprehensive guide will help you understand the error, why it occurs, and how to fix it.

## Table of Contents
1. [Understanding the Error](#understanding-the-error)
2. [Common Causes for the Error](#common-causes-for-the-error)
3. [Step-by-Step Guide to Fix the Error](#step-by-step-guide-to-fix-the-error)
4. [FAQs](#faqs)
5. [Related Links](#related-links)

## Understanding the Error
The "Referenced Script on This Behaviour is Missing" error occurs when Unity cannot find a script attached to a GameObject in your scene. This error prevents the script from running and may cause unexpected behavior in your game.

## Common Causes for the Error
1. **Script file missing or deleted**: If the script file has been accidentally deleted or moved, Unity won't be able to find it.
2. **Script file renamed**: If the script file has been renamed, Unity will lose its reference to the script.
3. **Class name changed**: If the class name within the script has been changed, Unity won't be able to recognize it.
4. **Compiler errors**: If there are any compiler errors in your project, Unity won't load the scripts until the errors are fixed.

## Step-by-Step Guide to Fix the Error
### Step 1: Identify the GameObject with the Missing Script
In the Unity console, click on the error message. This will highlight the GameObject with the missing script in your scene hierarchy.

### Step 2: Check if the Script File Exists
Make sure the script file is still present in your project's 'Assets' folder. If it's missing, recover it from a backup or recreate it.

### Step 3: Verify the Script Name and Class Name
Ensure that the script file name and the class name within the script match. If they don't, update either the file name or the class name to match each other.

### Step 4: Fix Compiler Errors
Check the Unity console for any compiler errors in your project. Fix these errors and Unity should be able to load the scripts again.

### Step 5: Reattach the Script
After completing the above steps, reattach the script to the GameObject by dragging the script file from the 'Assets' folder onto the GameObject in the scene hierarchy.

## FAQs
### Q1: What happens if I don't fix the 'Referenced Script on This Behaviour is Missing' error?
**A1**: If you don't fix the error, the script won't run, and this may lead to unexpected behavior in your game.

### Q2: Can I delete the missing script component from the GameObject?
**A2**: Yes, you can delete the missing script component. However, if the script is essential for your game to function correctly, it's better to fix the error and reattach the script.

### Q3: How can I avoid this error in the future?
**A3**: To avoid this error, make sure not to delete, move, or rename script files without updating the references in Unity. Also, ensure that you fix any compiler errors in your project.

### Q4: Will this error affect the performance of my game?
**A4**: This error alone won't affect the performance of your game. However, if the missing script is crucial for your game's functionality, it may lead to performance issues or unexpected behavior.

### Q5: Can I search for missing scripts in my entire project?
**A5**: Yes, you can search for missing scripts in your entire project using custom editor scripts or third-party tools like [Find Missing Scripts](https://assetstore.unity.com/packages/tools/utilities/find-missing-scripts-59144) from the Unity Asset Store.

## Related Links
- [Unity - Manual: Debugging Scripts](https://docs.unity3d.com/Manual/DebuggingScripts.html)
- [Unity - Scripting API: MonoBehaviour](https://docs.unity3d.com/ScriptReference/MonoBehaviour.html)
- [Unity - Manual: Console Window](https://docs.unity3d.com/Manual/Console.html)

$begingroup$

One of my game objects used to have a script that I have now deleted on purpose. Now it keeps saying this message as a warning:

The referenced script on this Behaviour is missing!

How can I rid of that?

asked Apr 22, 2014 at 15:24

Fabián's user avatar

$endgroup$

$begingroup$

Remove the missing reference from your GameObject. You attached your script to something, remove the now missing component, and done.

answered Apr 22, 2014 at 15:28

kat0r's user avatar

kat0rkat0r

3061 silver badge6 bronze badges

$endgroup$

3

$begingroup$

Another potential reason why this error might occur is that your script file name and script class name are different. For example:

Incorrect Setup

enter image description here

enter image description here

Correct Setup

enter image description here

enter image description here

answered Jun 23, 2022 at 7:25

Gunt.r's user avatar

Gunt.rGunt.r

1012 bronze badges

$endgroup$

You must log in to answer this question.

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

.

Помогите найти причину ошибки

Помогите найти причину ошибки

Вообщем, делаю ИИ по уроку, но заместо поворота противника, игрок телепортируется в противника и не может двигаться (только двигается камера). Вот код:

Код: Выделить всё
using UnityEngine;

public class MobAI : MonoBehaviour {
   public Transform target; 
   public int moveSpeed;
   public int rotationSpeed;

       private Transform myTransform;

      void Awake() {
   myTransform = transform;
   }

      void Start() {
   GameObject go = GameObject.FindGameObjectWithTag("Player");
   target = go.transform;
   }

      void Update() {
   Debug.DrawLine(target.position,myTransform.position,Color.yellow);
   myTransform.rotation = Quaternion.Slerp(myTransform.rotation,Quaternion.LookRotation(target.position = myTransform.position),rotationSpeed*Time.deltaTime);
   }
}

Аватара пользователя
kast96
UNец
 
Сообщения: 21
Зарегистрирован: 09 мар 2012, 12:42

Re: Помогите найти причину ошибки

Сообщение allash 09 мар 2012, 13:26

ну во-первых надо не присваивать (target.position = myTransform.position), а вычитать =)
а во-вторых надо дописать
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;

allash
UNец
 
Сообщения: 46
Зарегистрирован: 15 ноя 2011, 22:38

Re: Помогите найти причину ошибки

Сообщение kast96 10 мар 2012, 09:30

Исправил, полоска от врага к игроку рисуется, но враг не поворачивается. Движение я пока не ставлю, чтоб не отвлекало. И пишет еще лог предупреждения: The referenced script on this Behaviour is missing!
Вот на всякий случай код:

Аватара пользователя
kast96
UNец
 
Сообщения: 21
Зарегистрирован: 09 мар 2012, 12:42

Re: Помогите найти причину ошибки

Сообщение AndreyMust19 10 мар 2012, 09:45

The referenced script on this Behaviour is missing!

Это редактор пишет в том случае, если потерялась ссылка на скрипт в компоненте одного из объектов. Это происходит если переименовать/удалить скрипт в файловом менеджере, а не в редакторе. Если кликнуть на ошибку, открывается explorer, а не показывается сбойный объект.
Пощелкайте по объектам, у к-х есть скрипты и найдите компонент, у к-го в поле Script вместо имени скрипта написано Missing и снова укажите нужный скрипт. Либо опытным путем определите — какой из объектов в игровом режиме перестал себя вести как раньше.

Нужна помощь? Сами, сами, сами, сами, сами… делаем все сами

AndreyMust19
Адепт
 
Сообщения: 1119
Зарегистрирован: 07 июн 2011, 13:19

Re: Помогите найти причину ошибки

Сообщение kast96 11 мар 2012, 12:58

Ну а почему не поворачивается к игроку?

Аватара пользователя
kast96
UNец
 
Сообщения: 21
Зарегистрирован: 09 мар 2012, 12:42

Re: Помогите найти причину ошибки

Сообщение commandoby 06 июл 2014, 17:58

AndreyMust19 писал(а):

The referenced script on this Behaviour is missing!

Это редактор пишет в том случае, если потерялась ссылка на скрипт в компоненте одного из объектов. Это происходит если переименовать/удалить скрипт в файловом менеджере, а не в редакторе. Если кликнуть на ошибку, открывается explorer, а не показывается сбойный объект.
Пощелкайте по объектам, у к-х есть скрипты и найдите компонент, у к-го в поле Script вместо имени скрипта написано Missing и снова укажите нужный скрипт. Либо опытным путем определите — какой из объектов в игровом режиме перестал себя вести как раньше.

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

Аватара пользователя
commandoby
UNIт
 
Сообщения: 64
Зарегистрирован: 28 июн 2012, 22:33
Откуда: Пинск.Беларусь
Skype: commando_by
  • Сайт


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

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

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



Понравилась статья? Поделить с друзьями:
  • Как мне найти свой регион в майнкрафт
  • Как составить деловой документации
  • Как найти олицетворение в текстах
  • Как составить бизнес план мастеру маникюра для соц контракта
  • Как найти судебную практику по дтп