Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 /
This post has been wikified, any user with enough reputation can edit it.
avatar image
1
Question by Two_Click_Tools · Oct 09, 2014 at 07:13 PM · c#addcomponent

How to check if a script component exists before adding it?

I'm checking if a script exists before optionally using it like this:

 MyClass myClass = go.AddComponent< MyClass >();
  if(myClass != null){
       // Do some stuff with it if it exists
  }
  else{
       //no worries, continue anyway
  }

But of course, if it doesn't exist, the main script won't compile in the first place, with an error: "The type or namespace name `MyClass' could not be found. Are you missing a using directive or an assembly reference?"

Is there a way around this?

Thanks

Comment
Add comment · Show 2
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 robertbu · Oct 09, 2014 at 11:58 PM 1
Share

I'm not sure about your error, but to check, use GetComponent():

 $$anonymous$$yClass myClass = go.GetComponent<$$anonymous$$yClass>()
 if (myClass == null) {
      myClass = go.AddComponent<$$anonymous$$yClass>();
 }
avatar image Two_Click_Tools · Oct 10, 2014 at 02:30 AM 0
Share

Thanks, but that would still require checking if the script exists in the project first. It's tricky!

2 Replies

· Add your reply
  • Sort: 
avatar image
2

Answer by Kiwasi · Oct 10, 2014 at 12:38 AM

This is tricky. The answer involves using reflection. In general I tend to recommend avoiding reflection. I'll give you some terms and steps to help your google search. If I get some free time I'll come back and write the code.

  • Get your type name as a string

  • Check if the type exists

  • Check to see if the type is a component

  • Call add component with your type

Here are a few stack overflow questions to check out.

http://stackoverflow.com/questions/8499593/c-sharp-how-to-check-if-namespace-class-or-method-exists-in-c

http://stackoverflow.com/questions/18650005/check-if-a-class-exists-within-the-current-net-assembly

http://stackoverflow.com/questions/2528216/how-to-detect-the-existence-of-a-class-at-runtime-in-net

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 Two_Click_Tools · Oct 10, 2014 at 02:40 AM 0
Share

Thanks very much for those links, I understand the problem better now, and it's clearly not trivial. Working through it now... (Apologies, dont have permission to upvote yet)

avatar image
0

Answer by astracat111 · Oct 17, 2016 at 05:00 AM

To invoke a method by string name:

         var assembly = Assembly.GetExecutingAssembly ();
         var types = assembly.GetTypes();
         foreach (var type in types) { 
             var methods = type.GetMethods ();
             foreach (var method in methods) { 
                 if (method.Name == "MyMethodTest") { 
                     //Run method here
                     method.Invoke (null, null);
                 }
             }
         }


And to check if a method exists, returning 0 if there are no methods of that name anywhere in your assembly, 1 if there is a single one, and 2 if there are duplicate named ones:

     int MethodExistsOrNot = 0;
     var assembly = Assembly.GetExecutingAssembly ();
     var types = assembly.GetTypes();
     foreach (var type in types) { 
         var methods = type.GetMethods ();
         foreach (var method in methods) { 
             if (method.Name == "MyMethodTest") { 
                 //One more MyMethodTest exists
                 MethodExistsOrNot += 1;
             }
         }
     }

     if (MethodExistsOrNot > 1) { 
         Debug.Log ("There is more than one existence of this method. Methodname must be unique to invoke from assembly.");
     }
     if (MethodExistsOrNot == 0) {
         Debug.Log ("No method exists in the assembly with that name.");
         MethodExistsOrNot = 0;
     }
     if (MethodExistsOrNot == 1) {
         Debug.Log ("Method exists!");
     }

     Debug.Log (MethodExistsOrNot);


The code will be slow and isn't optimized, but you can throw that into a function. Call the System.Reflection; namespace at the beginning of your file as well.

Comment
Add comment · 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

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Attach C# Script on runtime 1 Answer

Copy a script from one gameobject to another? 1 Answer

AddComponent( 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