Toggle Flashlight

Hello everyone! I want to make my flashlight toggleable and this is my script so far :

using UnityEngine;
using System.Collections;

public class ToggleFlashlight : MonoBehaviour {

    void Update() {

        if (Input.GetKeyUp(KeyCode.F)) {

            if (gameObject.activeSelf == true) {
               
                gameObject.SetActive(false);
            }
            else if (gameObject.activeSelf == false) {

                gameObject.SetActive(true);
           
            }

        }

    }
}

I just don’t know what’s wrong with it. When I press F the Flashlight turns off, but I can’t turn it back on again. What am I missing?

activeSelf might not be correct. That will return true if the object is active, even if the parent is inactive.

See below for fixed script.
Try this:
```csharp
~~using UnityEngine;
using System.Collections;

public class ToggleFlashlight : MonoBehaviour {

private void Update() {

    if(Input.GetKeyUp(KeyCode.F)) {
        gameObject.SetActive(!gameObject.activeInHierarchy);
    }

}

}~~
```

I’m sorry, I haven’t been here the past days. Anyways, I tried the script, but the same thing happens. For comparison, here’s what the script looks like that I’m using:

using UnityEngine;
using System.Collections;

public class ToggleFlashlight : MonoBehaviour {

    public void Update() {

        if (Input.GetKeyUp(KeyCode.F)) {

            gameObject.SetActive (!gameObject.activeInHierarchy);
        }

    }
}

Oh I think this is a silly mistake on my part.

When you do “gameObject.SetActive(false)” on the current gameobject, that also stops all the components from updating, including this one. So what you want to do instead is something like this:

using UnityEngine;

public class ToggleFlashlight : MonoBehaviour {

    public Light light;

    private void Awake() {

        light = GetComponent<Light>();

    }

    private void Update() {

        if(light != null && Input.GetKeyUp(KeyCode.F)) {
            light.enabled = !light.enabled;
        }

    }
}

If you want to manually assign the light component in the inspector you can, but make sure to remove the Awake function or it will be overwritten there. This assumes that the light component is on the same gameobject. If the light is a child of the gameobject, use “GetComponentInChildren”.

1 Like

Amazing, learned a lot again :slight_smile: Thank you!