# How to disable script component while in game?

I'm trying to make a C# script to disable the First person controller script component for my character. I'm doing this so that while I'm controlling something else such as a vehicle, the only control script enabled at the time is the vehicle, and vice versa for when I'm not in the vehicle.

I did find a tutorial on the Unity Web site for Enabling and Disabling components but it uses a light component as an example, and I have no idea of how to do the same thing with a script component. I really appreciate any help I can get to solve this problem.

Thank you

This is the code in C# provided by the tutorial:

public class EnableComponents : MonoBehaviour
{
private Light myLight;

void Start ()
{
myLight = GetComponent<Light>();
}

void Update ()
{
if(Input.GetKeyUp(KeyCode.Space))
{
myLight.enabled = !myLight.enabled;
}
}
}

• Light is the script. In your case your script name will come there. Its simple as that. – Saad Anees Mar 28 at 12:50

Assume that you have a script like so:

public class CustomScript: MonoBehaviour
{
void Start ()
{
//does some stuff
}
void Update ()
{
//does some other stuff
}
}


Now, let's also assume you have a gameObject which has this script and also another script to enable / disable this script:

public class EnableDisableForCustomScript : MonoBehaviour
{
CustomScript myScript;
void Start ()
{
myScript = gameObject.GetComponent<CustomScript>();
}
void Update ()
{
if(Input.GetKeyUp(KeyCode.Space))
{
myScript.enabled = !myScript.enabled;
}
}
}


You can also extend the last part with two keys that will enable or disable at will:

void Update ()
{
if(Input.GetKeyUp(KeyCode.Space))
{
myScript.enabled = true; //enable the script when space is pressed
}
else if (Input.GetKeyUp(KeyCode.Escape))
{
myScript.enabled = false; //disable the script when escape is pressed
}
}


Remember, you need both scripts on the same object or you need to first find that object in the scene and then the component named as your script.

The only thing you need to change in that script is the call to GetComponent. Change <Light> to the name of the class which implements your 1st person controller behavior. So when your first person controller is implemented as a class FirstPersonController : MonoBehaviour, get a reference to it with GetComponent<FirstPersonController>(). The .enabled property is inherited from MonoBehaviour, so it is available on every scripted behavior.

Use this:

//your other object
public GameObject otherobj;


GameObject.Find("Cube").GetComponent<MoveObject>().enabled = false;