- Home /
Why can't I disable multiple components?
I recently watched a tutorial on how to disable multiple components but they were using an older version of unity, 5.2.1 to be exact. It's pretty much the same but it seems in Unity 2019.1.0a8 the enabled tag does not work. Anyone know what I can do to fix it?
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking;
public class PlayerSetup : NetworkBehaviour { [SerializeField] public Component[] ComponentsToDisable;
// Start is called before the first frame update
void Start()
{
if(!isLocalPlayer)
{
for (int i = 0; i < ComponentsToDisable.Length; i++)
{
ComponentsToDisable[i].enabled = false;
}
}
}
}
Answer by Bunny83 · Feb 23, 2019 at 11:04 PM
Components can't be disabled. If you look at the Component class documentation you will notice it doesn't have an enabled property. And it never has one. Only the derived class Behaviour (from which MonoBehaviour and some other Unity components are derived from) does have an enabled property.
Note that some Unity components are not derived from Behaviour but implement their own enabled property. This makes it difficult to handle several components at once. However there are only a few base classes which are important. Those are basically Behaviour, Renderer and Collider. Those should cover almost all components which have an enabled property. You would need to do:
for (int i = 0; i < ComponentsToDisable.Length; i++)
{
var behaviour = ComponentsToDisable[i] as Behaviour;
if (behaviour != null)
{
behaviour.enabled = false;
continue;
}
var rend = ComponentsToDisable[i] as Renderer;
if (rend != null)
{
rend.enabled = false;
continue;
}
var coll = ComponentsToDisable[i] as Collider;
if (coll != null)
{
coll.enabled = false;
continue;
}
}
There is no other way to handle all components which have an enabled property beside using reflection. However this is not really faster or simpler.
edit
If you want to be on the save side you can add this after the final if statement:
var type = ComponentsToDisable[i].GetType();
var property = type.GetProperty("enabled");
if (property != null)
property.SetValue(ComponentsToDisable[i], false, null);
Note that the tutorial you may have seen probably used UnityScript and not C#. UnityScript allowed dynamic code which was very slow but more flexible. However dynamic code was never supported on most AoT platforms like iOS.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
SetActive (true); Used the wrong way? 1 Answer
How do you disable a c# from a js script? 1 Answer
Component values don't get assigned 0 Answers