Enable all components of GameObject in Unity

Started by
6 comments, last by EddieK 5 years, 10 months ago

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?

Advertisement

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.

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):

https://www.youtube.com/watch?time_continue=1994&v=9-zDOJllPZ8

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):

https://www.youtube.com/watch?time_continue=1994&v=9-zDOJllPZ8

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?

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.

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 :)

"I could either watch it happen or be a part of it." - Elon Musk

Oh okey, thanks guys :)

This topic is closed to new replies.

Advertisement