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.
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
public class ToggleScript : MonoBehaviour
{
Canvas canvas;
void FixedUpdate()
{
if (Input.GetKey(KeyCode.X))
{
if (canvas.GetComponent<Canvas>().enabled == true)
{
canvas.GetComponent<Canvas>().enabled = false;
}
else
{
canvas.GetComponent<Canvas>().enabled = true;
}
}
}
}
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
use Update() because FixedUpdate() will very likely miss keystrokes of that edge-detect behavior for .GetKeyDown()
finally you need to set canvas in the first place. You are doing canvas.GetComponent() 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().enabled directly.
If it’s on another object, use a public reference and set it in the inspector like any other Unity thing.