- Home /
How to hide non-active button?
Hello. I am making a game, where the main character can talk with different NPCs. When he comes close to them (enters trigger collider), "TALK" button appears. When he goes away, the button should disappear. I made it with button.SetActive(true/false).
using UnityEngine;
public class NPCInteraction : MonoBehaviour {
public GameObject talkButton;
void OnTriggerEnter2D (Collider2D other) {
if (other.name == "Player") {
talkButton.SetActive(true);
Debug.Log(talkButton.activeSelf);
}
}
void OnTriggerExit2D (Collider2D other) {
if (other.name == "Player") {
talkButton.SetActive(true);
Debug.Log(talkButton.activeSelf);
}
}
}
The problem is: button always remains on the screen.
Wat.
As you can see, I made public variable talkButton
, so I can just drag any object (not just button) on it to test the script.
The button's active state changes correctly when I come close and go away, as I can see in debug window Debug.Log(talkButton.activeSelf);
Also the button's color changes to gray in hierarchy when it isn't active.
This is making me go completely bonkers when I try to understand whats going on. If I place another UI element (dialogue box for example) in the variable, it behaves exactly the same way (remains on the screen), but when I place entire UI (canvas), it works as intended (appears and disappears).
Later I wrote a new simple script to test this and put it into my canvas (UI):
public class UIController : MonoBehaviour {
public GameObject talkButton;
void Update () {
if (Input.GetKeyDown(KeyCode.Space)) {
talkButton.SetActive(!talkButton.activeSelf);
}
}
}
Exactly the same happens. Button remains on the screen. Same happens with any other UI element that I was testing except the entire canvas. Why do elements inside canvas remain there even deactivated? Do i have to make separate canvas for every element if I wanna toggle its state? I am going to get mad with this. HALP
In the first example, did you mean to do SetActive(false) on line 15?
Answer by Blaugrana · Jan 14, 2018 at 09:28 AM
try to change these things:
using UnityEngine;
public class NPCInteraction : MonoBehaviour {
public Button talkButton;
void OnTriggerEnter2D (Collider2D other)
{
if (other.name == "Player")
{
talkButton.gameObject.SetActive(true);
Debug.Log(talkButton.activeSelf);
}
}
void OnTriggerExit2D (Collider2D other)
{
if (other.name == "Player")
{
talkButton.gameObject.SetActive(false);
Debug.Log(talkButton.activeSelf);
}
}
}
Answer by danz_the_deadly · Jan 15, 2018 at 07:18 PM
Actually I stopped making the button active/non-active. Instead I added canvasgroup to button and made it non-interactable, non-blockable and transparent instead of non-active.
It works well and fast, but it requires 3 times more code.