Turning scripts off and on through scripting?

As the title says…is there a way to turn scripts attached to objects off and on from other scripts? Because I have a number of objects that spend most of their time not doing anything, so to avoid spending time uselessly cycling through Update()s doing nothing, as well as making game logic simpler, it would be nice to activate or deactivate the scripts on command.

It’s easy enough to activate/deactivate the objects themselves, but then they disappear when deactivated and I don’t want that. :wink: In the meantime I’ve made empties that only contain a script, so activating/deactivating the empties does work. It would be somewhat more convenient to do it directly though. I spent some time searching and not finding anything about this subject…apologies if it’s something obvious, as usual… :wink:

–Eric

i know of this in reference to physics more than anything. so i’m not sure if it’s what you’re after but search the docs/forum for sleep.

every script can be enabled individually.

enabled = false;

In the inspector this is visualized with the small check box.

http://unity3d.com/Documentation/ScriptReference/Behaviour.enabled.html?from=MonoBehaviour

Aha! I knew I just wasn’t looking hard enough…or was that the lack of sleep (I did try, honest)…anyway, many thanks!

@pete
Actually it’s not really about physics; I try to let the physics engine take care of that sort of thing and leave it alone. It’s about having scripts running that don’t need to be running, and just turning them on and off when I need to, instead of wasting time with extra coding in those scripts to accomplish the same thing. I could probably explain better with specific examples, but it’s a moot point now. :slight_smile:

–Eric

Yes, this is a very useful ability. I keep getting confused between “active” and “enabled” for various object classes, though.

in short, components can be enabled.
game objects on the other hand can be activated.

gameObject activity turns the whole game object on/off, as if the game object doesnt exist. No events or functions will be called. FindWithTag won’t find the object anymore etc.

enabled on components usually turns off the effect of the component but in the case of scripts, you still receive most events. While it seems a bit strange at first it’s really useful. Eg. you might have OnTriggerEnter function which you use to enable the object when it comes close to the player. So the behaviour is disabled because you dont want to process anything while the player is far away, but you still want to receive the trigger event, so you can enable the script when the player enters the trigger.