Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

flashlight is flickering ,not lighting when F key clicked

Discussion in 'Scripting' started by mowmizyd, Oct 12, 2020.

  1. mowmizyd

    mowmizyd

    Joined:
    Oct 11, 2020
    Posts:
    8
    i mean when i click F (flashlight enable/disable) it lights for like 1 frame, and it turns off, here is the code
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Flashlight : MonoBehaviour
    6. {
    7.     public Light flashLight;
    8.  
    9.     private bool isActive;
    10.  
    11.     // Use this for initialization
    12.     void Start ()
    13.     {
    14.         isActive = true;
    15.     }
    16.    
    17.     // Update is called once per frame
    18.     void Update ()
    19.     {
    20.         if (Input.GetKeyDown(KeyCode.F))
    21.         {
    22.             if(isActive == false)
    23.             {
    24.                 flashLight.enabled = true;
    25.                     isActive = true;
    26.             }
    27.         }   else if(isActive == true)
    28.             {
    29.                flashLight.enabled = false;
    30.             isActive = false;
    31.             }
    32.     }
    33. }
    34.  
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    On line 27 you're closing out the "if Input.GetKeyDown..." block with an extra '}'. Move that'}' to after line 31. This is why it's important to have good indentation and formatting oj your code.
     
    mowmizyd likes this.
  3. mowmizyd

    mowmizyd

    Joined:
    Oct 11, 2020
    Posts:
    8
    TYSM brudda :D
     
  4. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    As well as indenting your code correctly, you could also reduce it if you wish by simply toggling the boolean and setting the flashlight state to it. Like so;

    Code (CSharp):
    1. if (Input.GetKeyDown(KeyCode.F))
    2. {
    3.     //Toggle the boolean
    4.     isActive = !isActive;
    5.     //Set the flashlight enabled state
    6.     flashlight.enabled = isActive;
    7. }
     
    PraetorBlue likes this.