- Home /
Enable a script on object in c# help
Hi there,
I've looked around for ways to do this, but haven't found anything. I want to simply 'Enable' a script calling from a button press on another script. Once clicked, the script on the scene object is enabled. I have founds lots of .js examples. Do you have any examples of this in c#? Really stuck on this one.
Cheers
Rich
Answer by cmpgk1024 · Aug 16, 2013 at 02:15 PM
YourGameObject.GetComponent(YourScript).enabled = false;
or use generics - you must add using System.Collections.Generic
YourGameObject.GetComponent<YourScript>().enabled = false;
What if your Script Name has a spaces? Such as First Person Controller?
Technically, you're using the name of the class here, not the name of the script file, and class names never have spaces in them.
Answer by YoungDeveloper · Aug 16, 2013 at 02:17 PM
Hey, first you should getcomponent of that script.
ScriptNameToDisable script; //creates that script data type
script = GetComponent<ScriptNameToDisable>();
script.enabled = false;
Could you show me how this would look on the script? Not sure I understand. I have this button perfor$$anonymous$$g the action:
if(GUI.Button(boxRect,"","Panel4Button")) {
}
I guess I have to reference the scene object as well?
if(GUI.Button(boxRect,"","Panel4Button")) { //if your button is corrent
ScriptNameToDisable script;
script = GetComponent<ScriptNameToDisable>();
script.enabled = false;
}
You can get component on the go (in this function only when called), and after the function has finished, that data type will be deleted, which will free memory allocation.
Doesn't seem to work. I've added the code into the script, but nothing happens. Is this right?
TargetLostScript script; ///name of the script on the object
script = GetComponent<TargetLostScript>(); //name of the script
script.enabled = true; //this turns on the script
Thanks for your help.
Di I need to be referencing the Object that the script is on?
Oh, sorry i made a mistake. We need to find the gameobject name first to call it.
gameObject.GetComponent();
But the point here is, how do you want to get that object. Easy way would be attaching that script gameobject in a public variable;
So the final script:
public GameObject object; //drag the gameobject which have that script you want to disable, in the inspector.
if(GUI.Button(boxRect,"","Panel4Button")) { //or any if check
ScriptNameToDisable script;
script = object.GetComponent<ScriptNameToDisable>();
script.enabled = false;
}
Sorry for the mistake again.
Your answer

Follow this Question
Related Questions
Enable script (get "script" number?) 2 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
The name `UnityEditor' does not exist in the current context 3 Answers