Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Enable / Disable Canvas from script

Discussion in 'Scripting' started by FloatyPixel, Dec 28, 2015.

  1. FloatyPixel

    FloatyPixel

    Joined:
    Dec 11, 2015
    Posts:
    7
    Hello!

    I'm trying to make a shop for my game. But I can't make it work using the same button for opening and closing the Shop. It's like "Update" is too fast for it so it just opens and closes. In console I get message "Shop Is Opened" and "Shop Is Closed" at the same time. It works fine when I change the button but I need it on the same button.


    Code (CSharp):
    1. public Canvas shop;
    2. private bool shopOpened = false;
    3.  
    4. void Update ()
    5.     {
    6.         if (Input.GetKey(KeyCode.E) && shopOpened == false)
    7.         {
    8.             shop.enabled = true;
    9.             shopOpened = true;
    10.             Debug.Log ("Shop Is Opened");
    11.  
    12.             if (Input.GetKey(KeyCode.E) && shopOpened == true)
    13.             {
    14.                 shop.enabled = false;
    15.                 shopOpened = false;
    16.                 Debug.Log("Shop Is Closed");
    17.             }
    18.  
    19.         }
    20.  
    21.     }
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,744
    You have two problems.

    1. Use Input.GetKeyDown instead. GetKey returns true for every frame the key is held.

    2. After that, put your second input check into an 'else if', not one nested inside the main 'if' - otherwise, it'll execute both 'if' blocks, and just close it immediately.
     
  3. FloatyPixel

    FloatyPixel

    Joined:
    Dec 11, 2015
    Posts:
    7
    lol I forgot on "else if" *facepalm*
    Thank you