Within the Unity GUI next to each script attached to an object is a check box where you can activate or deactivate any script. This should be possible using a simple boolean within another script itself though. Thus my question is:
How can I script the activation and deactivation of specific scripts attached to an object?
I feel like it should be really simple but I can’t seem to find what I am looking for.
I found gameObject.GetComponent to get a specific script but there didn’t seem to be anything for turning them on and off.
To toggle the state of the script from some other script (if on another GO, may require a Find in there):
var myScript : ScriptName;
function Start () {
myScript = GameObject.GetComponent(ScriptName);
}
function Something () {
myScript.enabled != myScript.enabled;
}
All of this is needed to create a stable reference to the script BEFORE it is turned off. If you turn it off iwth GetComponent, the next GetComponent call will fail because GetComponent can’t find the script since it’s turned off. Same thing goes for unchecking the box in the Inspector – any code that’s looking for that script will fail to find it.
Keep in mind that all the enabled setting does is allow Update() and FixedUpdate() to be called automatically. If you’re making any other calls to the script, those will still go through.
Thanks everyone. That did the trick. Also thanks for giving me some more indepth information about the “.enabled” field. Good to know exactly what it does and doesn’t do.
I would assume that it disables all functions of a script outside of initalization functions such as Start. Though really I am just talking out of my ass, I’m not absolutely sure. Anyone want to shed some light?
I have another question for people as far a toggling components are concerned. If I wanted to toggle, say, a character controller how would I go about doing that?
It doesn’t have a little checkbox in the GUI to turn it on and off so I’m not sure if it has the “enabled” variable. Though the character controller is derived from GameObject and I would assume that it has the “active” variable. So does the active variable work? and if so, what is the proper declaration of it? if not, suggestions? Thanks in advance and many times over.
You know what? Screw my last question because the character controller can’t do what I want it to do and it certainly can’t do it in the time frame I need it to. So, if someone feels like answering that would be great but otherwise I’m just going to have to eventually redesign the entire system anyway.