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;
}
else
{
GetComponent<WanderingAI> ().enabled = false;
}
}
Answer by wornTunic · Sep 11, 2017 at 01:50 PM
Create a canvas in your scene by clicking
GameObject -> UI -> Canvas
Create a button under your canvas by clicking
GameObject -> UI -> Button
Create a public method in your NPC class that toggles the state of the npc:
public void ToggleState() { GetComponent<WanderingAI> ().enabled = !GetComponent<WanderingAI> ().enabled; //this changes the state from on to off and vice-versa }
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 yourToggleState()
method you created.
Note: You could put WanderingAI
inside a variable so you don't have to call GetComponent()
all the time
Your answer
Follow this Question
Related Questions
I create material with script but it does not render right 0 Answers
Creating Splines from empties in script 0 Answers
Call a function When a bool changes value? 2 Answers
How can i rotate all the child objects together at the same time ? 1 Answer
How can i give another name/number to the created Plane object name ? 0 Answers