Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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
0
Question by KodaL · Jun 14, 2011 at 08:47 PM · editor-scriptingnullreferenceexceptionaddcomponent

AddComponent giving NullReferenceException in Editor script

Having an issue using AddComponent to add a script to a newly created prefab. This is in C#. I have the script "scriptType1.js" located in my 'Assets\Scripts\' folder.

The errors I'm getting are as follow, but I have no idea what it all means. My script can't get past "AddType1Stuff()" function.

NullReferenceException: Object reference not set to an instance of an object CreatePrefabFromModels.AddType1Stuff (UnityEngine.GameObject newPrefab) (at Assets/Editor/CreatePrefabFromModels.cs:142) CreatePrefabFromModels.createNew (UnityEngine.GameObject obj, System.String localPath) (at Assets/Editor/CreatePrefabFromModels.cs:118) CreatePrefabFromModels.CreatePrefab (UnityEngine.GameObject prefab) (at Assets/Editor/CreatePrefabFromModels.cs:96) CreatePrefabFromModels.OnWizardCreate () (at Assets/Editor/CreatePrefabFromModels.cs:65) System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) Rethrow as TargetInvocationException: Exception has been thrown by the target of an invocation. System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) UnityEditor.ScriptableWizard.OnGUI () (at C:/BuildAgent/work/6bc5f79e0a4296d6/Editor/MonoGenerated/Editor/ScriptableWizard.cs:70) System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) Rethrow as TargetInvocationException: Exception has been thrown by the target of an invocation. System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) UnityEditor.HostView.Invoke (System.String methodName, System.Object obj) (at C:/BuildAgent/work/6bc5f79e0a4296d6/Editor/Mono/GUI/DockArea.cs:213) UnityEditor.HostView.Invoke (System.String methodName) (at C:/BuildAgent/work/6bc5f79e0a4296d6/Editor/Mono/GUI/DockArea.cs:206) UnityEditor.HostView.OnGUI () (at C:/BuildAgent/work/6bc5f79e0a4296d6/Editor/Mono/GUI/DockArea.cs:107)

CODE:

 using UnityEngine;
 using System.Collections;
 using UnityEditor;
 
 public class CreatePrefabFromModels : ScriptableWizard
 {
     
     public GameObject[] prefabsToCreate;
         
     [MenuItem ("Custom/Create Prefab from 3D Models")]
     static void CreateWizard ()
     {
         ScriptableWizard.DisplayWizard<CreatePrefabFromModels>("Create Prefab from 3D Models", "Apply");
     }
         
     void OnWizardCreate ()
     {
         foreach (GameObject prefabToCreate in prefabsToCreate)
         {
             CreatePrefab(prefabToCreate);
         }
     }
 
     static void CreatePrefab (GameObject prefab)
     {
         string localPath = "Assets/Prefabs/prefab_" + prefab.name.ToLower() + ".prefab";
         
         if (AssetDatabase.LoadAssetAtPath(localPath, typeof(GameObject)) )
         {
             if (EditorUtility.DisplayDialog("Are you sure?", "The prefab already exists. Do you want to overwrite it?", "Yes", "No"))
             {
             createNew(prefab, localPath);
             }
             else
             Debug.Log("File was not overwritten");
         }
         else
         {
             createNew(prefab, localPath);
         }            
     }
     
     
     static void createNew(GameObject obj, string localPath)
     {
         Object newPrefab = EditorUtility.CreateEmptyPrefab(localPath);    // create new empty prefab
         EditorUtility.ReplacePrefab(obj, newPrefab);                    // put the 3d model into the new prefab
         
         if (obj.name.ToLower().Contains("type1"))
         { 
             AddType1Stuff(newPrefab as GameObject);    // have to say 'as GameObject' since AddComponent won't work with an 'Object'
         }
         else if (obj.name.ToLower().Contains("type2"))
         {
             AddType2Stuff(newPrefab as GameObject);
         }
         else
         {
             Debug.Log("Object is not Type1 or Type2");
         }
         
         AssetDatabase.Refresh();
     
         GameObject clone = EditorUtility.InstantiatePrefab(newPrefab) as GameObject;
     }
     
     static void AddType1Stuff(GameObject newPrefab)
     {
         newPrefab.AddComponent<scriptType1>();
         newPrefab.AddComponent<MeshCollider>();
     }
     
     static void AddType2Stuff(GameObject newPrefab)
     {
         newPrefab.AddComponent<scriptType2>();
     }
 }
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

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Bunny83 · Jun 15, 2011 at 01:08 AM

If you use ReplacePrefab you should call AssetDatabase.Refresh(); and reload the prefab because the AssetDatabase isn't up to date.

Also it would make more sense to build your GameObject and then replace the prefab and not the other way round.

     if (obj.name.ToLower().Contains("type1"))
     { 
         AddType1Stuff(obj);
     }
     else if (obj.name.ToLower().Contains("type2"))
     {
         AddType2Stuff(obj);
     }
     else
     {
         Debug.Log("Object is not Type1 or Type2");
     }
     Object newPrefab = EditorUtility.CreateEmptyPrefab(localPath);
     EditorUtility.ReplacePrefab(obj, newPrefab);
     AssetDatabase.Refresh();
     newPrefab = AssetDatabase.LoadAssetAtPath(localPath,typeof(GameObject));

     GameObject clone = EditorUtility.InstantiatePrefab(newPrefab) as GameObject;


By the way, i don't recommend to use the "as" cast since it will return null when it can't be casted. The "normal" c-style cast will throw an Invalid-Cast-Exception if it can't be casted.

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 KodaL · Jun 15, 2011 at 01:49 AM 0
Share

Thanks, I'll try it out! Didn't realize I could add components like scripts directly to the 3d $$anonymous$$odel file, since it wouldn't let me drag and drop onto it from the inspector.

What is the other way to cast? I'm new to C#, and had seen 'as' somewhere so I used that.

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

2 People are following this question.

avatar image avatar image

Related Questions

NullReferenceException - Editor script using GetComponent after AddComponent 1 Answer

applying toon shading to all 3d meshes at once 1 Answer

Editor Window/Scriptable object - null problem 2 Answers

GetComponent and AddComponent with variables for Collider type 2 Answers

ReorderableList Custom Editor Count -> NullReferenceExeception 1 Answer


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