I have an array which using the inspector I would like to add components to that are currently assigned to a gameobject.
public Component[] playerComponentsToDisable;
Once added I will be calling a function using a foreach to loop through the array and disable all of the components/scripts within it. The problem is that I can’t seem to be able to assign any components into the array using the inspector. When I try to select a component for any element of the array, I get a select list of gameobjects instead of components.
Using the standard 3rd Person Controller as an example, I would like to add its Character Controller component and Third Person Controller component into the array via the inspector. I am not assigning them via GetComponent because the script with the array is going to be assigned to many different gameobjects and so it would be a lot of extra coding for each, compared to simply selecting the components needing to be disabled via the inspector. Am I missing something, or can this not be done in this way? I haven’t tried using a list yet but shouldn’t this work for either?
Hi, sorry for necroposting but this is the link that came up first, but I think I got a more elegant solution to the problem.
// Create an array of Behaviours, which are Components that can be enabled/disabled.
public Behaviour[] _componentsToDisable;
// Then you can disable them whenever you want.
foreach (var component in _componentsToDisable)
{
component.enabled = false;
}
Hi, if I understood well your problem: I think it’s caused by the fact that a Component is not made to exist by itself: it has to be contained by a GameObject. Then, when referencing a Component in the Inspector, Unity references the GameObject that contains the Component and not the Component itself (EDIT: this may be over simplified and even false, I guess it also has to do with Types and derivation as it would work with an array of “MyMonobehaviour” instead of an array of Component containing any component-derived type)(EDIT2: must be because Unity must know what type is the class it deserializes and then can’t serialize an array of some base class containing derived classes… hummm, my brain’s Start() wasn’t called correctly this morning
If you want to enable or disable Components in some GameObjects in your scene based on a list you can edit in the inspector (that’s what I understood from your question): one solution could be to store strings. In the inspector, you could store an array of strings that you would each format like “gameobjectname.componenttype”. Then, in the code, use the string to call GameObject.Find(“”) and then GetComponent(“”) (after splitting each one). It may not be very convenient if you have a lot of components to enable and disable but quite quick to code. You could also “cache” those lists into a Component during the Start() so it’s faster to enable/disable during the game.