C# Toggle TextMesh

I don’t understand why this isn’t working, it’s driving me nuts! I’ve done scripts very similar to this and they’ve all worked just fine. I’m using 3D Text or TextMesh in my game, which is set to false when the game starts but when a button in the scene is clicked, it shows up, and acts as a toggle. I don’t understand it. I’ve tried several variations but nothing works. For some reason it either shows up but doesn’t go away or it doesn’t show up and doesn’t appear when the button’s pressed. It’s very frustrating. I’m wondering if there’s something I haven’t yet done to make it work, like getting a reference to the MeshRenderer. At the moment my 3D Text is assigned as a GameObject. I haven’t used 3D Text much so I’m a bit stumped. Coming here’s usually a last resort for me because I like to search online for a solution or figure it out myself (I still have a lot to learn about C#). I appreciate any help. I’ll post the code that’s driving me up the wall. This script is attached to the 3D Text itself (which already has text written on it via the Inspector) but to toggle it there’s a button to click, hence the OnClick() method. Have I missed something?

using UnityEngine;
using System.Collections;

public class BootUpText : MonoBehaviour {

    //public TextMesh bootUpText;
    public GameObject bootUpText;
    bool showText;


    // Use this for initialization
    void Start () {
        //bootUpText = GameObject.Find ("Boot Up Text").GetComponent<TextMesh> ();
        showText = false;


   
    }
   
    // Update is called once per frame
    void Update () {
        if (showText) {
            bootUpText.SetActive(!bootUpText.activeInHierarchy);

        } /*else if (!showText){
            bootUpText.SetActive (false);
        }*/
   
    }



    public void OnClick()
    {
        showText = !showText;
    }
}

You shouldn’t be setting whether it is active in Update, only set it when it needs to be (in your case, the OnClick function).

As it is now, while showText is true the bootUpText is continually flipping between active and inactive every frame.

I changed “(!bootUpText.activeInHierarchy)” to “true” which now shows the text in the scene, which is odd as in the start function, it’s set to false. It might be my Boolean.
Also, I tried removing the statements from Update but that didn’t work either. Thanks though.

using UnityEngine;
using System.Collections;

public class BootUpText : MonoBehaviour {
    public GameObject bootUpText;
    bool showText;

    void Start () {
        showText = false;
        bootUpText.SetActive(showText);
    }

    public void OnClick()
    {
        showText = !showText;
        bootUpText.SetActive(showText);
    }
}
1 Like

Yes! It worked! Thank you very much.