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 /
avatar image
1
Question by zombience · Mar 14, 2013 at 11:46 PM · c#getcomponenttypegeneric

get component type at runtime using generic GetComponent in C#

hello, so I find myself using a lot of objects that have several children that either contain audio, particle systems, materials, etc. It often happens that I need to disable them for all of the transform children without destroying the object.

I've written recursive searches to disable the specific type of component that I need at that time, but how can I write a generic script that just takes any component as an argument and searches for it? This is what I've come up with so far, and it doesn't work since Component itself cannot be enabled/disabled, but only the class types that inherit from it (e.g. rigidbody, light, etc). How can I rework this so that I can use a generic?

 using UnityEngine;
 using System.Collections;
 
 public static class CheckComponent 
 {
     public static T Check<T> (this Transform t) where T : Component
     {
            T component = t.GetComponent<T>();
      
        if(component == null)
        {
             Debug.LogError("Search for component type " + typeof(T) + " yielded no results", t);
        }
      
        return component;
     }
     
     public static void RecursiveDisable<T> (this Transform t) where T : Component
     {
         T component = t.GetComponent<T>();
         
         if(component == null)
         {
             Debug.LogError("Attempting to disable component type " + typeof(T) + ", but " + t + " has none");
         }
         else
         {
             //component.enabled = false; // not possible, only children that inherit from component can be enabled/disabled
         }
         if(t.childCount > 0)
         {
             foreach(Transform child in t)
                 child.RecursiveDisable<T>();
         }
         else
         {
             //done
         }
         
     }
 }
 
 
Comment
Add comment · Show 3
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 hoy_smallfry · Mar 14, 2013 at 11:55 PM 0
Share

Grrr. I tried doing this once, but I can't remember if I came up with a solution, and even then, I don't have the source anymore to look up!

avatar image hoy_smallfry · Mar 15, 2013 at 12:00 AM 0
Share

I do remember, however, that the solution isn't pretty for the same reasons you are having trouble with it; Component has no derivable enabled flag. Off the top of my head, I suppose you could use the as keyword to check if the Component can cast to one of the most basic "toggle-able" Components. The downside is that it's no longer a compile-time condition, which is probably one of the reasons you are making it a generic.

avatar image zombience · Mar 15, 2013 at 12:11 AM 0
Share

this is one of the few times where i've considered using javascript, because i think it can handle this kind of scenario

1 Reply

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

Answer by Bunny83 · Mar 15, 2013 at 12:13 AM

Components can't be disabled, right. That's why there is the type Behaviour which is derived from Component which introduces the "enabled" property. A lot components are derived from Behaviour including MonoBehaviour (so all your scripts included). However there are some other built-in components which bring their own enabled property, so they don't share it via inheritance. Two important ones are the Collider and the Renderer base-class.

There are other components as well which can be enabled in some way (ParticleSystem, Rigidbody) but don't have an enabled property. A more general approach is to simply disable the gameobject the component is attached to. This will disable the components as well.

See the inheritance tree for more insight.

edit
If you just care about the major components, you could do something like that:

 if(component == null)
 {
     //[...]
 }
 else
 {
     if (component is Behaviour)
         (component as Behaviour).enabled = false;
     else if (component is Collider)
         (component as Collider).enabled = false;
     else if (component is Renderer)
         (component as Renderer).enabled = false;
 }

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 hoy_smallfry · Mar 16, 2013 at 01:15 AM 0
Share

Yes, this is exactly what I meant - most basic "toggle-able" Components

avatar image zombience · Mar 16, 2013 at 01:15 AM 0
Share

thanks! it worked as expected. I often need to keep the objects themselves from being destroyed while disabling components. For example, stopping multiple particle emitters, but allowing the object to continue to exist so that the particles may complete their lifecycle.

I'm glad that I can at least write all the if/else statements once and be done with it. I appreciate the help

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

13 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

Related Questions

Generic Component Declaration 1 Answer

Multiple Cars not working 1 Answer

Referencing a c# component script from JS script 2 Answers

Distribute terrain in zones 3 Answers

Is it possible to use a variable as a Type? 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