0
\$\begingroup\$

I don't know if this matters, but I'm using Unity 2D. The code only turns the flashlight off, but not back on.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class flashlightonoff : MonoBehaviour
{
    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;
    }
}
\$\endgroup\$
5
  • \$\begingroup\$ Is this script on the same object that it's turning off, or in one of its children? \$\endgroup\$
    – DMGregory
    May 30 at 18:21
  • \$\begingroup\$ Same object that its turning off \$\endgroup\$
    – Henry
    May 30 at 19:51
  • \$\begingroup\$ And you expect the Update method to still be called on the script, even while its GameObject is inactive? What do the docs have to say about that? \$\endgroup\$
    – DMGregory
    May 30 at 19:58
  • \$\begingroup\$ Ok i dont fully understand but i just set it too the flashlight light instead of the actual flashlight and that works. Thanks! \$\endgroup\$
    – Henry
    May 30 at 21:21
  • \$\begingroup\$ Want to post your solution as an Answer below? \$\endgroup\$
    – DMGregory
    May 30 at 21:22

Your Answer

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

Browse other questions tagged or ask your own question.