- Home /
Gameobject script enable weird behavior
I have a rather simple gameobject with three scripts, amongst which a simple one with an OnMousedown() function, that performs correctly and prints to console.
I have the need to disable the simple script after three clicks, and I thought well this seems pretty straightforward so I came up with this:
int maxclicksallowed = 3;
int clicks = 0;
void Update() {
//do the update stuff
}
void OnMouseDown() {
if (clicks > maxclicksallowed) {
//this actually works: the script gets disabled in the inspector
gameObject.GetComponent<thisscriptclass>().enabled = false;
print("how dare you click so much, I'm deactivating this script");
}
else {
//do the stuff i normally do
//...
clicks++;
}
}
Curious and unexpected thing is, despite the script being disabled in the inspector (the checkbox gets unflagged), mouse clicks on the object will still print the message, so WTF?
I don't like the idea of destroying the component script since it holds runtime state variables of the object that I'd need to save in some convolute way, and I don't like the idea of using a boolean condition, since the object will keep calling its update function "for nothing" (since it'll skip thanks to the false boolean condition mentioned).
So I'm ultimately wondering: what's the best way to 'disable' a script and prevent it's execution and Update calls until reactivation?
Thanks
Answer by fredpointzero · Aug 16, 2011 at 10:06 AM
Just checkout the Monobehaviour reference at unity3d.com:
Note: The checkbox for disabling a MonoBehavior (on the editor) will only prevent Start(), Awake(), Update(), FixedUpdate(), and OnGUI() from executing. If none of these functions are present, the checkbox is not displayed.
OnMouseDown
will still be executed on your GameObject.
You should deactiveate the entire GameObject (gameObject.active = false). If you want to separate components, just create a child to your game object, and add your component and disable the child on over click.
NB : you can use this
to refer to gameObject.GetComponent<thisscriptclass>()
Your answer
Follow this Question
Related Questions
Enabling/Disabling Multiple Tagged objects 1 Answer
Errors when trying to enable script on gameobject. 0 Answers
gameObject.GetComponent("Script").enabled = true not working 5 Answers
Acessing scripts in other game objects with prefabs, without using GameObject.Find 1 Answer
Snap object in game using script? 2 Answers