0
\$\begingroup\$

So I have a flashlight battery script I created and I need to know how do you make the battery variable go down every few seconds(whatever time you set.) I tried InvokeRepeating but it was an absolute disaster (The battery variable just went down really fast and ignored my script). Anyways this is the code I have:

void Update ()
{
    if (light == false) {
        battery+=0;
    }
    if (light == true) {
        battery--;//This is what I want to have every few seconds
    }

    if (battery == 0) {
        myLight.enabled = false;
        light =false;
        battery++;
        InvokeRepeating("invoke", 1, 0.01F);
    }
}

void invoke(){
    light = false;
    myLight.enabled = false;
}
\$\endgroup\$
  • \$\begingroup\$ This question is actually about how to fix your code, I think it's a poor question. Also, in the future, please only include the code related to the problem in your question. \$\endgroup\$ – MichaelHouse Nov 30 '14 at 1:37
3
\$\begingroup\$

You're on the right track with InvokeRepeating. However, three issues:

  1. You're currently calling your invoke method every .01 seconds.

  2. Your invoke method disables your myLight component, rather than decreasing battery.

  3. Your invoke method is a very confusing name.

I'm not sure you're calling InvokeRepeating in a good spot, but I'll let you test that :)

I'd suggest changing your invoke method to something like this:

void DecreaseBattery(){
    battery--;
}

Then edit your InvokeRepeating call:

InvokeRepeating("DecreaseBattery", 30f, 30f);

This will invoke DecreaseBattery after 30 seconds, and then every 30 seconds thereafter.

If you ever need to cancel or restart the InvokeRepeating call, you may want to use CancelInvoke(); somewhere to ensure multiple repeats don't overlap.

|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.