Enabling & Disabling Script via On Click

Hi Everyone,

Still new to Unity and have seemed to have hit a brick wall. I badly need some help please.

I have a wandering script attached to a non playable character but I would love to be able to toggle just this script via On Click GUI button so I can choose if the character wanders around of just stands idle. At the moment I can turn the script on from off, but thats it. Could use some help.

Here is the script;

bool on = true;


	void Start () {

		if (!on)
			//enabled = true;
			GetComponent<WanderingAI>().enabled = true;
			GetComponent<WanderingAI> ().enabled = false;
  1. Create a canvas in your scene by clicking GameObject -> UI -> Canvas

  2. Create a button under your canvas by clicking GameObject -> UI -> Button

  3. Create a public method in your NPC class that toggles the state of the npc:

    public void ToggleState() {
    GetComponent ().enabled = !GetComponent ().enabled; //this changes the state from on to off and vice-versa

  4. Connect the method to your button by navigating to your button in hierarchy and finding On Click() list at the bottom of your button component. There, on the left side, you’ll choose your npc gameObject in the scene, and from the dropdown list (left), you should find and choose your ToggleState() method you created.

Note: You could put WanderingAI inside a variable so you don’t have to call GetComponent() all the time