- Home /
Toggling a script on/off using the keyboard?
^ This.
i'm making a showroom, and the object i'm showing is rotating due to a script i wrote...now i want to be able to toggle this script on and off by pressing R on the keyboard...this is what i got so far
if(Input.GetKeyDown("r"))
{
GetComponent("NewBehaviourScript").enabled = false;
}
if(Input.GetKeyDown("t"))
{
GetComponent("NewBehaviourScript").enabled = true;
}
}
disabling works just fine, re#enabling does not.
any help?
thanks in advance
h4wkeye
BTW : Yes i know i assigned 2 diff buttons, it's just to test the actual functionality of it
Answer by Eric5h5 · Mar 31, 2011 at 08:33 AM
If the script is disabled, then Update (which presumably is where this code is) isn't running, so naturally it can't reenable itself. You'd want to enable/disable it from another script. (As an aside, better to not use strings with GetComponent...slower and not type-safe.)
A bit curious, so ins$$anonymous$$d of putting a string there I suppose getting the Type would work, but what if we would have multiple objects of the same type possible to grab from GetComponents? How to identify the specific component needed. Or could we cache the string _name in a constructor or is that pretty much the same deal as hardcasting it?
Answer by h4wkeye · Mar 31, 2011 at 08:45 AM
Alright guys, thanks to Eric5h5 it's working now. i'll share my script here in case someone else needs it.
Enable.js
function Update () {
if(Input.GetKeyDown("r"))
{
GetComponent("NewBehaviourScript").enabled = !GetComponent("NewBehaviourScript").enabled;
}}