- Home /
how to disable a script without setting script.enabled?
I want to disable a script after it's done it's thing after a certain time. It won't let me use its "enabled" property, though. not when I want it, anyway:
It works just fine inside Start(), for instance:
Start() {this.enabled = false; //works fine}
But when I try to create a function, it says it can't be invoked:
void OnEnable() {
Invoke("StopBlinking()", blinkDuration);
}
void StopBlinking() {
this.enabled = false;
}
Any ideas what's going on and how I can work around that? I don't want to set the whole game object inactive but I also don't want this script to keep doing it's update thing.
Answer by Bunny83 · May 07, 2015 at 10:53 PM
The error is quite simple. Invoke doesn't execute "code" but executes a method with a certain name. However the brackets "()" are not part of the name. Use:
Invoke("StopBlinking", blinkDuration);
I actually wanted to use "Invoke" as a tag for this question, but it wouldn't let me because I can't create new tags yet..
@Cinno$$anonymous$$an: "invoke" is already a tag. I've added it.
Answer by CinnoMan · May 07, 2015 at 10:47 PM
if anyone else has encountered this, I've worked around this by doing the following:
void Update () {
t = (Mathf.Sin(Time.time * blinkFrequency) + 1) / 2;
sr.color = Color.Lerp(Color.black, Color.white, t);
durationCounter++;
if (durationCounter == blinkDuration) {
sr.color = Color.white;
this.enabled = false;
}
}
This code won't work right because it's framerate-dependent.
you're right to point that out, however, in my use case, it doesn't matter, it's precise enough.