Search Unity

Turning on and off light with the same button!

Discussion in 'Scripting' started by ande04b, Sep 4, 2012.

  1. ande04b

    ande04b

    Joined:
    Aug 29, 2012
    Posts:
    119
    Hello forum.

    I'm trying to turn on and off the light form my frashlight object, using the same Mouse button (Mouse3)...
    But it doesn't work...

    The code agrees to let me turn ON the light using the button, but when I click that same button again,
    the light should turn off.. But it doesn't. It just stays on...

    The code is:

    Code (csharp):
    1. private var lightOn : boolean = false;
    2.  
    3. function Update () {
    4.  
    5.     if(Input.GetKey(KeyCode.Mouse2)  lightOn) {
    6.         lightOn = false;
    7.         light.intensity = 0;
    8.        
    9.     }
    10.     if(Input.GetKey(KeyCode.Mouse2)  !lightOn ) {
    11.         lightOn = true;
    12.         light.intensity = 5;
    13.         }
    14. }
    Any clues on how to fix this?
     
  2. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
  3. HolBol

    HolBol

    Joined:
    Feb 9, 2010
    Posts:
    2,887
    A quick Google Search gets this:

    Code (csharp):
    1. function Update() {
    2.  
    3. if (Input.GetKeyDown(KeyCode.Mouse2)) {
    4.  
    5. if (light.enabled == true) {
    6.  
    7. light.enabled = false;
    8.  
    9. }
    10. else{
    11.  
    12. light.enabled = true;
    13. }
    14. }
    15. }
    16.  
     
  4. ande04b

    ande04b

    Joined:
    Aug 29, 2012
    Posts:
    119
    Thanks guys. :)
    I'm gonna play around with those.
     
  5. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    If lightOn is true, the if statement runs and sets lightOn to false, so the next if statement runs too. This is where "else if" becomes of paramount importance. (Also you need to use Down or Up rather than just GetKey.) Or you can just toggle it like this, though you have to ensure that light.intensity is 0 or 5 to start with or else it won't work right:

    Code (csharp):
    1. function Update () {
    2.     if (Input.GetMouseButtonDown(2)) {
    3.         light.intensity = 5 - light.intensity;
    4.     }
    5. }
    --Eric
     
  6. ande04b

    ande04b

    Joined:
    Aug 29, 2012
    Posts:
    119
    Thanks Eric, and it works now guys.

    Thanks so much for your help. :)