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 Djaydino · Jul 29, 2017 at 08:53 AM · variablecomponentenable

Enable/Disable a Component by using a String Variable for the Component name

Hi, I need to Enable a component by string.

i am trying to this : go.GetComponent<myComponent>.Enabled = true; but i want to be a variable so now i am getting my component like this :

 aComponent = go.GetComponent(componentNameString);

But i can't do :

 aComponent.Enable = True;


the 'componentNameString' is given by the user in the inspector that's the main reason why i need to use a string.

Comment
Add comment · Show 6
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 pako · Jul 29, 2017 at 10:32 AM 1
Share

There's no problem with the code you posted, except what is probably a typo (you missed the 'd' at the end of enabled:

 //Correct
 aComponent.Enabled = True;
 
 //Wrong
 aComponent.Enable = True;
 
 

However, if I understand well, I think that the real problem is that you have to specify the name of the component before compilation takes place, so that the compiler knows what to do with it, but you want to specify it at run time. What I don't understand is how a "user" will have access to the Inspector.

$$anonymous$$AYBE this can be done through Reflection (or maybe not), but I've never had the need to use Reflection, so I can only tell you to check C#/Reflection to see if it can be done, or maybe someone who has expertise with Reflection can help you out.

avatar image Djaydino pako · Jul 29, 2017 at 08:10 PM 0
Share

Hi, Both do not work and i also tried using reflection but thanks anyway to try :)

avatar image ShadyProductions Djaydino · Jul 29, 2017 at 09:33 PM 0
Share

I'm pretty sure it should be lowercase .enabled = true;

Show more comments
avatar image pako · Jul 29, 2017 at 09:27 PM 0
Share

This is strange! Anyway, I'm not 100% clear on what you're trying to do. $$anonymous$$aybe if you give some more detail, it'll be easier to focus on the problem at hand.

2 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by Bunny83 · Jul 30, 2017 at 03:12 AM

A Component doesn't have an "enabled" property. Only some specific derived classes have one. For example your own scripts get their enabled property from the Behaviour class. The MonoBehaviour class is derived from Behaviour. So if the components you want to enable / disable are scripts (components derived from MonoBehaviour) or other components derived from Behaviour you can simply cast the result of GetComponent to "Behaviour". This allows you to use it's enabled property.

Be careful that when the actual component that is returned can't be casted to Behaviour an exception would be thrown.

Have a look at this class hierachy(it's old but the core classes are there). As you can see even many built-in components are derived from Behaviour. However there are some components that also have an enabled property but are not derived from Behaviour (like Renderer and all it's child classes).

To cover most components you can do it like this:

 // C#
 var comp = go.GetComponent(componentNameString);
 Behaviour be = comp as Behaviour;
 if (be != null)
 {
     be.enabled = true;
 }
 else
 {
     Renderer rend = comp as Renderer;
     if (rend != null)
         rend.enabled = true;
 }

Another way might be to use reflection to search for an actual property with the name "enabled". However reflection can cause many problems if not used properly and is generally slow. Though it would allow to set the "enabled" property of any kind of component.

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 Djaydino · Jul 30, 2017 at 06:52 AM 0
Share

Hi. Thanks this seems to work for most components, the only ones that i found so far are colliders. But i can live with that, as there are already specific actions for Enable colliders

here is a copy from the (Playmaker) action script.

 using UnityEngine;
  
 
 namespace HutongGames.Play$$anonymous$$aker.Actions
 {
     [ActionCategory(ActionCategory.GameObject)]
     [Tooltip("Destroys a Component of an Object. WARNING! COLLIDERS DO NOT WOR$$anonymous$$ WITH THIS ACTION and Some Components $$anonymous$$ight not work!")]
     public class ActivateComponent : FsmStateAction
     {
         [RequiredField]
         [Tooltip("Place Component Object here n/WARNING COLLIDERS DO NOT WOR$$anonymous$$!!")]
         public FsmObject component;
         [Tooltip("Activate / Deactivate the Component")]
         public FsmBool Activate;
 
         public override void Reset()
         {
             component = null;
             Activate = false;
 
         }
 
         public override void OnEnter()
         {
 
             DoActivateComponent();
 
             Finish();
         }
 
         
         void DoActivateComponent()
         {
 
             if (component.Value == null)
             {
                 LogError("No Component Selected");
                 Debug.Log("No Component");
             }
             else
             {
                 Behaviour be = component.Value as Behaviour;
 
                 if (be != null)
                 {
                     be.enabled = Activate.Value;
                 }
                 else
                 {
                     Renderer rend = component.Value as Renderer;
                     if (rend != null)
                         rend.enabled = Activate.Value;
                 }
             }
         }
     }
 }

avatar image Bunny83 Djaydino · Jul 31, 2017 at 04:13 AM 0
Share

Well you can just add another case for the Collider base class to support all colliders as well. In addition you can add a "last resort" fallback using reflection. That way it would be the most versatile. I also would use early-exits in this case. Something like this:

 void DoActivateComponent()
 {
     if (component.Value == null)
     {
         LogError("No Component Selected");
         Debug.Log("No Component");
         return;
     }

     Behaviour be = component.Value as Behaviour;
     if (be != null)
     {
         be.enabled = Activate.Value;
         return;
     }

     Renderer rend = component.Value as Renderer;
     if (rend != null)
     {
         rend.enabled = Activate.Value;
         return;
     }

     Collider col = component.Value as Collider;
     if (col != null)
     {
         col.enabled = Activate.Value;
         return;
     }

     var t = component.Value.GetType();
     var p = t.GetProperty("enabled", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
     if (p != null && p.CanWrite && p.PropertyType == typeof(bool))
     {
         // maybe log a warning like this
         //Debug.Log("ActivateComponent:: reflection fallback for class'"+t.FullName+"'");
         p.SetValue(component.Value, Activate.Value, null);
         return;
     }

     LogError("selected component doesn't have an 'enabled' property");
     Debug.Log("selected component doesn't have an 'enabled' property");
 }
avatar image
0

Answer by xRinaruk · Jul 29, 2017 at 11:26 PM

I think it should works if you get all assembiles and then get all types. If you have them all, just compare to string and you will have the one you are looking for. Then you can use GetComponent and set enable/disable.

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

73 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 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 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 avatar image avatar image avatar image avatar image

Related Questions

How to select BoxColliders of children and disable them? 1 Answer

Change variable of ex2D Sprite using the component ExScreenPosition via code .js script 0 Answers

Accessing a variable of a script from another scene. 7 Answers

How to deactivate something when holding down a key? 1 Answer

enable disable variable of a script from another script 4 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