- Home /
Toggle with key input only turning off
Very noob question and I've tried to see if this was answered somewhere else but couldn't find a solution.
This is the code I'm using. The problem I'm having is that the object disappears, but when I press the assigned key again, it won't reappear which is what I'd like for it to do.
I don't know much about coding and I'm just starting to learn.
public GameObject glasses;
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("glassesKey"))
glasses.SetActive(!glasses.activeSelf);
}
Is this script attached to the "glasses" GameObject itself? If so, an inactive GameObject won't run its Update() function.
For reference, you could also give yourself some more feedback in the console to ensure things are working as expected:
void Update()
{
if(Input.GetButtonDown("glassesKey"))
{
glasses.SetActive(!glasses.activeSelf);
Debug.Log(string.Format("{0}: \"glassesKey\" pressed: {1}.activeSelf = {2}", gameObject.name, glasses.name, glasses.activeSelf));
}
}
Edit: gave example a little more detailed diagnostic output
Thanks! I'll try adding the debug and see what it give me!
Yes, it's attached to the glasses GameObject itself but I think I also tried it on a separate game object just for the script
Yep that was the problem lol. Ty! When I made a game object with only the script before I had stupidly parented it to the object I was turning off XD
Answer by DrHerringbone · Jul 18, 2021 at 06:56 AM
Quick question is this script on the glasses object?
If so, you are disabling the object that looks for your key input! Try putting this script on the camera.
Oh! I will try this out and get back to you! Makes a whole lot of sense!!!
Your answer

Follow this Question
Related Questions
Need to press key twice to react 1 Answer
Scoring system by pressing a series of particular keys 2 Answers
How can I detect which key or mouse button was pressed? 1 Answer
Toggle button help 1 Answer
Aimdown Sights Toggle 1 Answer