- Home /
Disable all components but 1 on a gameobject
Component[] comps = this.gameObject.GetComponent<Component>();
for(int i=0;i<comps.length;i++)
{
Component c = comps[i];
Type t = c.GetType();
if(t.FullName == "TrackRenderer")
{
this.gameObject.GetComponent<TrackRenderer>().enabled = true;
}
else
{
this.gameObject.GetComponent<c>().enabled = false;
}
}
The error I get with this is: The type or namespace name 'c' could not be found.
I have a few gameobjects with this script attached to it, each one has a few different scripts attached to it, but they always have a TrackRenderer. The thing I want to do is disable all those scripts and keep the TrackRenderer enabled. Anyone have suggestions?
Answer by Herman-Tulleken · Jul 29, 2011 at 05:17 PM
The reason you get the error is that c
is a variable, and not a type. Here is one way to do it: set all components inactive, and then simply switch on the TrackRenderer
.
Note, you don't have to reference this.gameObject, you can use the method inherited from MonoBehaviour straight.
Edit: Incorporated the comments below.
MonoBehaviour[] comps = GetComponents<MonoBehaviour>();
foreach(MonoBehaviour c in comps)
{
c.enabled = false;
}
GetComponent<TrackRenderer>().enabled = true;
Thanks for the quick reply and tips!
At the c.enabled = false line I get the following error:
Type 'UnityEngine.Component' does not contain a definition for enabled
ah, yes that's right... enabled is not a variable of 'Component' but a feature of 'Behaviour', 'Collider', 'Particle Emitter' and 'Renderer' only (unless I missed one)... other Components can't be enabled/disabled ...
You could use if (c.enabled != null) {c.enabled = false}
, I think?
Greetz, $$anonymous$$y.
I also noticed that if I leave the line: Component[] comps = GetComponent();
I get an error: Cannot implicity convert type 'UnityEngine.Component' to 'UnityEngine.Component[]'
but if I switch GetComponent to GetComponents, I get the enabled error
hmm... looks like a little bug to me. Error-message should be: 'Cannot implicity convert type 'UnityEngine.Component' to 'UnityEngine.Component [ ]', I think... Greetz, $$anonymous$$y.
edit: nonsense, I made a thinking-error.
Of course the if-statement won't fix the error...
just because the derived classes of your components do have the 'enabled' variable doesn't mean we can access it.
After all, we just collected the non-derived component-class which simply still doesn't have 'enabled'. ^.^'
if all the components are behaviours, then collect the $$anonymous$$onoBehaviours ins$$anonymous$$d of components.
$$anonymous$$onoBehaviour[] behavs = GetComponents< $$anonymous$$onoBehaviour >();
foreach($$anonymous$$onoBehaviour c in behavs)
{
c.enabled = false;
}
This way, you probably won't need GetComponent().enabled = true;
because renderer isn't $$anonymous$$onoBehaviour and won't be disabled in the first place.