Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
18
Question by DtBeloBrown · Apr 15, 2010 at 11:28 PM · editoreditor-scriptingmissing

How do I Remove null components ( i.e. "Missing(Mono Script)" ) via editor script?

I have made a script somewhat similar to this one: http://answers.unity3d.com/questions/5020/searching-a-project-for-missing-mono-script

But rather than just finding the null entries, I simply want to sweep through and delete them all. By that I mean remove the null references from the GameObjects's list of Components.

The documentation for GameObject.AddComponent notes that there is no such thing as RemoveComponent, requiring you to call Object.Destroy() to remove that entry. This is impossible because there is no object to Destroy.

Creating a new GameObject and adding the components of the old one to it would invalidate any references to it.

Is there a way to do this without laboriously clicking through the UI?

NEW EDIT: (in light of comments below)

Are these references to some funny objects representing a missing script that the overloaded == operator is treating as equal to null? No, because calling DestroyImmediate() does nothing, and trying to actually de-reference the pointer causes a null reference exception. It must be that there are null pointer entries in the list, and the list is not modifiable by editor script.

Here is the demonstration code:

[MenuItem("Custom/Remove Missing Script Entries")]
public static void Do() {
    foreach (Transform t in Selection.transforms) {
        Debug.Log(t.GetComponents(typeof(Component)).Length);
        foreach (Component c in t.GetComponents(typeof(Component))) {
            if (c == null){
                Debug.Log("NULL");
                // throw caution to the wind and destroy anyway!!! AHAHHAHAHAH!!!
                GameObject.DestroyImmediate(c);
                // awwww nothing happened.  still there.
            }
            else
                Debug.Log(c.GetType());
        }
    }
}
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

17 Replies

· Add your reply
  • Sort: 
avatar image
13

Answer by VildNinja · Mar 21, 2019 at 03:37 PM

They have added a fix for this in 2019.1

https://docs.unity3d.com/2019.1/Documentation/ScriptReference/GameObjectUtility.RemoveMonoBehavioursWithMissingScript.html

Edit: Code example

 [MenuItem("Auto/Remove Missing Scripts Recursively")]
 private static void FindAndRemoveMissingInSelected()
 {
     var deepSelection = EditorUtility.CollectDeepHierarchy(Selection.gameObjects);
     int compCount = 0;
     int goCount = 0;
     foreach (var o in deepSelection)
     {
         if (o is GameObject go)
         {
             int count = GameObjectUtility.GetMonoBehavioursWithMissingScriptCount(go);
             if (count > 0)
             {
                 // Edit: use undo record object, since undo destroy wont work with missing
                 Undo.RegisterCompleteObjectUndo(go, "Remove missing scripts");
                 GameObjectUtility.RemoveMonoBehavioursWithMissingScript(go);
                 compCount += count;
                 goCount++;
             }
         }
     }
     Debug.Log($"Found and removed {compCount} missing scripts from {goCount} GameObjects");
 }

Edit2: Sorry didn't see @AlanMattano posted this in a comment a while ago.

Edit3: For this to work on inactive Objects and prefabs, the code is a bit more complicated:

 using System.Collections.Generic;
 using System.Linq;
 using UnityEngine;
 using UnityEditor;
 public static class FindMissingScriptsRecursively
 {
     [MenuItem("Auto/Remove Missing Scripts Recursively Visit Prefabs")]
     private static void FindAndRemoveMissingInSelected()
     {
         // EditorUtility.CollectDeepHierarchy does not include inactive children
         var deeperSelection = Selection.gameObjects.SelectMany(go => go.GetComponentsInChildren<Transform>(true))
             .Select(t => t.gameObject);
         var prefabs = new HashSet<Object>();
         int compCount = 0;
         int goCount = 0;
         foreach (var go in deeperSelection)
         {
             int count = GameObjectUtility.GetMonoBehavioursWithMissingScriptCount(go);
             if (count > 0)
             {
                 if (PrefabUtility.IsPartOfAnyPrefab(go))
                 {
                     RecursivePrefabSource(go, prefabs, ref compCount, ref goCount);
                     count = GameObjectUtility.GetMonoBehavioursWithMissingScriptCount(go);
                     // if count == 0 the missing scripts has been removed from prefabs
                     if (count == 0)
                         continue;
                     // if not the missing scripts must be prefab overrides on this instance
                 }
 
                 Undo.RegisterCompleteObjectUndo(go, "Remove missing scripts");
                 GameObjectUtility.RemoveMonoBehavioursWithMissingScript(go);
                 compCount += count;
                 goCount++;
             }
         }
 
         Debug.Log($"Found and removed {compCount} missing scripts from {goCount} GameObjects");
     }
 
     // Prefabs can both be nested or variants, so best way to clean all is to go through them all
     // rather than jumping straight to the original prefab source.
     private static void RecursivePrefabSource(GameObject instance, HashSet<Object> prefabs, ref int compCount,
         ref int goCount)
     {
         var source = PrefabUtility.GetCorrespondingObjectFromSource(instance);
         // Only visit if source is valid, and hasn't been visited before
         if (source == null || !prefabs.Add(source))
             return;
 
         // go deep before removing, to differantiate local overrides from missing in source
         RecursivePrefabSource(source, prefabs, ref compCount, ref goCount);
 
         int count = GameObjectUtility.GetMonoBehavioursWithMissingScriptCount(source);
         if (count > 0)
         {
             Undo.RegisterCompleteObjectUndo(source, "Remove missing scripts");
             GameObjectUtility.RemoveMonoBehavioursWithMissingScript(source);
             compCount += count;
             goCount++;
         }
     }
 }
Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image NeatWolf · Mar 21, 2019 at 03:47 PM 0
Share

Aw, finally! Now we only need another to get rid of ghost gameobjects and we're done :P

avatar image Schmaggis · Dec 29, 2019 at 05:07 PM 0
Share

Hello! Sadly the Code does not find any $$anonymous$$issing Scripts :-/

int count = GameObjectUtility.Get$$anonymous$$onoBehavioursWith$$anonymous$$issingScriptCount(gameObject); Debug.Log($"Found {count} missing scripts"); count = GameObjectUtility.Remove$$anonymous$$onoBehavioursWith$$anonymous$$issingScript(gameObject); Debug.Log($"Removed {count} missing scripts");

Count is always 0 even if gameObject does have "null-scripts".

With the old method it still finds the missing scripts but the "prop.DeleteArrayElementAtIndex" ist nit supported any more in Unity 2019... Is there another way to delete missing scripts from the serializedObject-Property "m_Component"? Thanks!

avatar image theonciest · Oct 25, 2021 at 02:28 AM 0
Share

Yes!! This is the one that helped me. Thank you so much

avatar image
11

Answer by SunnySunshine · Jan 27, 2015 at 11:59 AM

By using this editor script, you can select all objects that are missing scripts, and then just delete them using the component menu.

Note that this will only work for missing scripts of the same type.

 [MenuItem("MyMenu/SelectMissing")]
 static void SelectMissing(MenuCommand command)
 {
     Transform[] ts = FindObjectsOfType<Transform>();

     List<GameObject> selection = new List<GameObject>();

     foreach(Transform t in ts)
     {
         Component[] cs = t.gameObject.GetComponents<Component>();

         foreach(Component c in cs)
         {
             if (c == null)
             {
                 selection.Add(t.gameObject);
             }
         }
     }

     Selection.objects = selection.ToArray();
 }


alt text


screen-shot-2015-01-27-at-125708-pm.png (24.5 kB)
Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image akasurreal · Aug 30, 2015 at 11:10 PM 2
Share

This works great, thanks.

avatar image Kjurek · Oct 13, 2017 at 12:13 PM 0
Share

Just perfect. Thx!

avatar image
10

Answer by beck · Dec 27, 2014 at 08:14 AM

Ran into this myself and ended up with a working solution. Only works in the editor of course.

 [MenuItem("Edit/Cleanup Missing Scripts")]
 static void CleanupMissingScripts ()
 {
     for(int i = 0; i < Selection.gameObjects.Length; i++)
     {
         var gameObject = Selection.gameObjects[i];
         
         // We must use the GetComponents array to actually detect missing components
         var components = gameObject.GetComponents<Component>();
         
         // Create a serialized object so that we can edit the component list
         var serializedObject = new SerializedObject(gameObject);
         // Find the component list property
         var prop = serializedObject.FindProperty("m_Component");
         
         // Track how many components we've removed
         int r = 0;
         
         // Iterate over all components
         for(int j = 0; j < components.Length; j++)
         {
             // Check if the ref is null
             if(components[j] == null)
             {
                 // If so, remove from the serialized component array
                 prop.DeleteArrayElementAtIndex(j-r);
                 // Increment removed count
                 r++;
             }
         }
         
         // Apply our changes to the game object
         serializedObject.ApplyModifiedProperties();
     }
 }
Comment
Add comment · Show 11 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image beck · Dec 27, 2014 at 08:22 AM 0
Share

Just want to note that I found out that the components reappear after reloading assemblies. However, if you perform this function, save the scene, and then change scenes, the fix sticks. It's hacky, but it works for me. Would love to see a more stable solution if someone finds one.

avatar image xiaomu beck · Oct 23, 2015 at 09:46 AM 0
Share

I get the same trouble, Did you find a solution ?

avatar image meat5000 ♦ xiaomu · Oct 23, 2015 at 10:09 AM 0
Share

If you are trouble removing a "$$anonymous$$issing Script" Component, simply drop a script into it, then remove it, in Editor.

Save.

Show more comments
avatar image IgorAherne beck · Sep 16, 2017 at 12:15 PM 0
Share

will this fix the issue at the end of the function?

 UnityEditor.Scene$$anonymous$$anagement.EditorScene$$anonymous$$anager.$$anonymous$$arkSceneDirty(gameObject.scene);
avatar image Gerold_Meisinger · Mar 03, 2016 at 07:44 AM 0
Share

Thanks for the solution! Btw: If you iterate the array in reverse you can omit keeping track of deleted elements. I also marked the GameObjects dirty. Works for me in U 5.1.4 but Unity crashes with a memory alloc error on changing scene afterwards. It still works though!

avatar image zero_null Gerold_Meisinger · May 31, 2016 at 01:27 PM 0
Share

Hey Hi @Gerold_meisinger

Can you tell me how you set GameObjects dirty ? Please

avatar image IgorAherne zero_null · Sep 17, 2017 at 02:51 AM 0
Share
 UnityEditor.EditorUtility.SetDirty(myGameObject);

you can also wrap it in preprocessor like this

 #if UNITY_EDITOR
 UnityEditor.EditorUtility.SetDirty(myGameObject);
 #endif

this will exclude this portion of code when the game is built, as if it never existed; Useful when you need to include "UnityEditor" functionality right into a $$anonymous$$onobehavior

avatar image NeatWolf · Jul 29, 2018 at 01:04 PM 0
Share

Thanks, in Unity 2018.2.1f1 I found myself with ALL gameobjects and prefabs in the project with an invisible script missing.

That meant that I had a "You are trying to replace or create a prefab from the instance 'Arch_Door_04_Preset' that references a missing script. This is not allowed. Please change the script or remove it from the game object. UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr) " every time I tried to apply changes from an instance to a Prefab.

Now I should only adapt your script to work on the whole Scene and Project Hierarchy and I should be able to save the project, which got corrupted in some way, and I didn't even noticed when!

avatar image AlanMattano · Jan 30, 2019 at 12:40 AM 1
Share

In the new Unity2019.1 API notes I read:

Editor: Added GameObjectUtility.Get$$anonymous$$onoBehavioursWith$$anonymous$$issingScriptCount and GameObjectUtility.Remove$$anonymous$$onoBehavioursWith$$anonymous$$issingScript to be able to remove $$anonymous$$onoBehaviours with a missing script from a game object.

avatar image VildNinja AlanMattano · Mar 25, 2019 at 10:13 AM 0
Share

Sorry didn't see you posted this before now. I've added a code example of this below.

avatar image
4

Answer by jonas-echterhoff · Jun 28, 2010 at 08:50 AM

I believe there is currently no easy solution to do this in scripting. The internal implementation when you pick "Remove Component" from the popup menu is in C++, where all MonoBehaviour components are just belonging to a MonoBehaviour class. Once these are passed to C#, they get the class types of their scripts, or, if the script is empty, then null, which cannot be used to destroy the object.

You might be able to get a pointer reference to the actual MonoBehaviour component which you could call delete on, by iterating through all the GameObjects properties using the SerializedObject class, but that probably takes same time to get to work, if it is possible at all.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Bunny83 · May 12, 2012 at 03:20 PM 0
Share

Just want to add that i've just tried to get a usable reference to the $$anonymous$$onoBehaviour, but it seems there's really no way. I used the SerializedObject class to get all component references, but even there it's just null.

I've digged quite deep into the editor and realized that the default inspector also uses a serialized object to display the GUI. The editor creates a SerializedObject from a reference, but this reference seems to get passed from the native code side. $$anonymous$$aybe it's possible to "hack" into the private members of the editor that displays the $$anonymous$$onoBehaviour with reflection, but beside that it's not a good idea to use relfection that way, it won't help much since the information what $$anonymous$$onoScript was used by this Behaviour is gone.

avatar image
4

Answer by DannyLZS · Jun 19, 2017 at 06:57 PM

Wrote a solution

https://pastebin.com/DLuE2Ze9

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image TooManySugar · Aug 20, 2018 at 11:30 AM 0
Share

THAN$$anonymous$$ YOU!!! THIS WOR$$anonymous$$S PERFECTLY, this should be the accepted answer

avatar image TheGameLearner TooManySugar · Nov 04, 2019 at 07:34 AM 0
Share

Running into the following after using this:

 Transform has 'ReflectionProbeAnchor$$anonymous$$anager::kChangeSystem' change interests present when destroying the hierarchy. Interests must be deregistered in Deactivate.
 UnityEditor.EditorApplication:Internal_CallGlobalEventHandler()


Can you tell me what can I do to avoid it?

  • 1
  • 2
  • 3
  • 4
  • ›

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

23 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Searching a project for "Missing (Mono Script)" 5 Answers

in-editor cloning of game objects 1 Answer

Size of the header of the EditorWindow 1 Answer

Stop a MonoBehavior from being addable as a script? 0 Answers

How To Best Match Editor GUI Content Heights 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges