Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Simple GameObject Hide/Unhide with bool!!!

Discussion in 'Scripting' started by dick, May 14, 2021.

  1. dick

    dick

    Joined:
    Sep 6, 2014
    Posts:
    90
    Hello,

    In my script, a bool turns true whenever a Key is held down in the update, and turns false when it's not held down. (this works)

    Code (CSharp):
    1. void Update()
    2. {
    3. myBool = Input.GetKey(KeyCode.G);
    4. }
    However, when i want a GameObject to be SetActive according to that bool, it won't work and the bool stays true, even when the key is let go. This is what i put in for turning on the GO in the script

    Code (CSharp):
    1. GO.SetActive(!Input.GetKey(G));
    Why is this? Can someone help with the GO being SetActive when the key is being held down and vice-versa? Thank you!!
     
  2. Code (CSharp):
    1. var keyPressed = false;
    2.  
    3. // [...]
    4.  
    5. if (Input.GetKeyDown(KeyCode.G)) keyPressed = true;
    6. if (Input.GetKeyUp(KeyCode.G)) keyPressed = false;
    7.  
    8. // [...]
    9.  
    10. GO.SetActive(keypressed); // Shows only while the button is pressed.