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

Toggle canvas element via input

Discussion in 'Scripting' started by Jeffey_101, Jun 6, 2019.

  1. Jeffey_101

    Jeffey_101

    Joined:
    Jul 12, 2018
    Posts:
    21
    I am trying to make it so when the X key is pressed, all my UI elements under my canvas will turn on or off. I have tried to use .SetActive and .enabled, but neither seem to work. Please send help.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEditor;
    4. using UnityEngine;
    5. using UnityEngine.UI;
    6.  
    7. public class ToggleScript : MonoBehaviour
    8. {
    9.     Canvas canvas;
    10.     void FixedUpdate()
    11.     {
    12.         if (Input.GetKey(KeyCode.X))
    13.         {
    14.             if (canvas.GetComponent<Canvas>().enabled == true)
    15.             {
    16.                 canvas.GetComponent<Canvas>().enabled = false;
    17.             }
    18.             else
    19.             {
    20.                 canvas.GetComponent<Canvas>().enabled = true;
    21.             }
    22.             }
    23.     }
    24. }
    25.  
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    Couple of things:

    1. you want Input.GetKeyDown() because that will detect the moment of pressing. The method you use returns true every frame that the key is down

    2. use Update() because FixedUpdate() will very likely miss keystrokes of that edge-detect behavior for .GetKeyDown()

    3. finally you need to set canvas in the first place. You are doing canvas.GetComponent<Canvas>() which looks on the current canvas (probably null) for a canvas, which causes a null reference.

    If the canvas is on your current object, just use GetComponent<Canvas>().enabled directly.

    If it's on another object, use a public reference and set it in the inspector like any other Unity thing.
     
  3. Jeffey_101

    Jeffey_101

    Joined:
    Jul 12, 2018
    Posts:
    21
    Thank you! Works wonders.
     
    Kurt-Dekker likes this.