- Home /
Trouble with Adding a Component that is already Disabled
Hi Folks,
Really at a loss on this one.
I'm using AddComponent to add a script to a GameObject and it is added in the "enabled = false" state.
This is the code that I'm using to add the script
if(SC.GetComponent<SceneController_Game_Mode_CS>() == null) {
SC.AddComponent("SceneController_Game_Mode_CS");
I'm not sure how this happens? Can a script be saved as disabled, so that when it is added it retains that state?
If so, how can I resave it as enabled?
I really don't know what to do with this one.
Thank you for your help.
Answer by stevethorne · Feb 27, 2014 at 07:50 PM
Not sure why the issue is happening to you but you could write
( ( SceneController_Game_Mode_CS ) SC.AddComponent( "SceneController_Game_Mode_CS" ) ).enabled = true;
Hey Steve,
Thanks so much for the quick response, however I tried this and I got the following:
error CS1061: Type UnityEngine.Component' does not contain a definition for
enabled' and no extension method enabled' of type
UnityEngine.Component' could be found (are you missing a using directive or an assembly reference?)
I've also tried enabling it immediately after adding it but, that still leaves the "Awake()" routine running and causes me grief.
Thanks.
You'll have to cast your component to what you want to enable in order to do that.
What Awake() grief are you talking about?
hmm, can you give me a code example of the cast-ing you're suggesting as I'm not sure how to cast the "enabling" of the component, or I'm just confused :)
Awake() grief = it seems that the Awake() function runs when the script is added even though it is disabled and that is forcing me to rearrange some variable instantiations (I think this is the correct word here).
Awake is called no matter what, it's similar to a constructor. Even if the script is disabled, it will be called.
As for the casting I've updated my answer to fix that.
Yep, got that about Awake :)
And that casting is slick as $n0+ :) and works great!
Thanks Steve!