The question is answered, right answer was accepted
Set GUI Text active/inactive by clicking on a button?
Hello, I created a GUI Text and a GUI Button. Now, by clicking on the button, the GUI Text has to be activated or deactivated when it's already displayed. I tried to attach a script to the button, but it doesn't really work...
using UnityEngine;
using System.Collections;
public class Help : MonoBehaviour {
public GameObject helpText;
void Start() {
helpText.SetActive(false);
}
public void onClick() {
if(helpText.activeSelf) {
helpText.SetActive(false);
}
else {
helpText.SetActive(true);
}
}
}
And can't find answers to similar problems here... most of them are outdated for Unity 3 or 4... don't know, how the "On Click()" in the button settings shall work.
Is there an easy way to do this?
Thanks for help.
Answer by KujaEx · Sep 27, 2015 at 04:03 PM
Okay, I watched now this tutorial: https://unity3d.com/learn/tutorials/modules/beginner/ui/ui-button
And made it that way with that script:
using UnityEngine;
using System.Collections;
public class Help : MonoBehaviour {
public GameObject startHelpText;
void Start() {
startHelpText.SetActive(false);
}
public void switchHelp(GameObject helpText) {
if(helpText.activeSelf) {
helpText.SetActive(false);
}
else {
helpText.SetActive(true);
}
}
}
I put that Script on an empty object and put that object on the "On Click ()" thing in the button and choose the "switchHelp(GameObject helpText) " in there. It's working now... but I thought it could be easier...
Answer by Rytje · Sep 27, 2015 at 02:25 PM
Your script doesn't know what helpText is. You probably need to use GameObject.Find() or something. You don't have to call the method you want to call with the button OnClick. You can call it anything as long as it is public I think. In your button you need to go to the OnClick method, select your script and select your public method.
The script don't have to know it. When it's public you can simply drag and drop the GameObject on this variable in the Inspector. When I put my Script into the "On Click ()" option I can't choose any method in there. And when I put the Text GameObject itself into the "On Click ()", I can only say, that it has to change to active OR inactive, but not to look before what it is, like in my script.
Follow this Question
Related Questions
C# - A way to set UI gameObject as active and then inactive when pressed a second time 0 Answers
How do I start with text inactive? 1 Answer
how to do a if statement to activate and deactivate a button 1 Answer
How to keep bool true even when other method try to set it off 0 Answers
SetActive not reacting on Buttonclick 0 Answers