r/UnityHelp • • May 29 '21

PROGRAMMING Whats wrong with my code?

This code is supposed to turn my flashlight sprite on and off when i press E, but right now it only turns it off and wont turn it back on. Heres the code

public class flashlightonoff : MonoBehavior { public static bool flashlightisoff = false; public GameObject Flashlight;

    void Start()
    {
            Flashlight.SetActive(true);
    }

   void Update()
   {
           If (Input.GetKeyDown(KeyCode.E)){
                   If (flashlightisoff)
                   {
                           ON();
                   }
                   else
                   {
                           OFF();
                   }
       }
}

void ON()
{
        Flashlight.SetActive(true);
        flashlightisoff =  false;
}

void OFF() { Flashlight.SetActive(false); flashlightisoff = true; } }

3 Upvotes

2 comments sorted by

2

u/SteveTDMiner Jun 03 '21

I agree with u/Asylation. I would say make the flashlight object the child of an empty object and the empty object is the one with the script

1

u/Asylation Helped Community May 29 '21

I'm going to assume the script is attached to the game object you are deactivating. If a game object is deactivated, methods like Update() in the scripts attached to it (or it's naturally deactivated children) won't run.