# Enable all components of GameObject in Unity

## Recommended Posts

Hi, so I have this script:

foreach(Behaviour behaviour in gameObject.GetComponentsInChildren<Behaviour>()
behaviour.enable = true;

It works, but only enables all custom made scripts. For example MeshRenderer doesn't get enabled, same goes for BoxCollider and so on. So how would I enable ALL components of the game object?

##### Share on other sites
Posted (edited)

Never mind, I figured out a different way of doing things. My problem was that to Instantiate an object programatically I needed to have that object to already be in the hierarchy. This didn't makes sense for bullets, because I didn't want a bullet laying around somewhere at the beggining of the game, when no shots were made. So instead I decided to disable all the components so that the bullet wouldn't be visible and wouldn't move and collide with things. And after Initialize(gameObject) I wanted to enable all those components of the new game object. But now I discovered prefabs, so I no longer need an instantiate game object to create a bullet.

Edited by EddieK

##### Share on other sites

You should still instantiate Eddie, and use gameObject.setActive to turn on and off the bullets. Instantiate will still be costly I think, even from a prefab.

This is one way of doing the pooling (I actually saw this after I did my bullets, I used it for particle effects):

##### Share on other sites
2 minutes ago, lawnjelly said:

You should still instantiate Eddie, and use gameObject.setActive to turn on and off the bullets. Instantiate will still be costly I think, even from a prefab.

This is one way of doing the pooling (I actually saw this after I did my bullets, I used it for particle effects):

Oh so what you're saying is that I should initialize many bullets at the start of the game, and then instead of initializing during runtime I should enable/disable them when needed to save up on performance?

##### Share on other sites

Yep, as far as I understand it (I have only been using unity a month though! :) ). I am using pooling for (nearly) everything, including sound.

##### Share on other sites

Collider and MeshRenderer are components but do not derive from Behaviour like other components do.

For both of these components you will need to get the components and set .enabled outside of your foreach loop,

Collider col = GetComponent<Collider>();
if(col != null)
col.enabled = false;

MeshRenderer mr = GetComponent<MeshRenderer>();
if(mr != null)
mr.enabled = false;

This is the correct way to do this

##### Share on other sites

Oh okey, thanks guys

## Create an account

Register a new account

• 11
• 19
• 12
• 9
• 34
• ### Forum Statistics

• Total Topics
631398
• Total Posts
2999840
×