show / hide text on UI via script

I need to display the text in a UI canvas after certain conditions has been met.

I have a canvas called “Restart Screen” and a text called “hsLabel” which is attached inside Restart Screen.

So far I tried this.

public Text hsLabel;       

public GameObject restartScreen;

void Start(){
restartScreen.SetActive (false);
hsLabel = GetComponent<Text> ();
hsLabel.enabled = false;
}

void OnTriggerEnter2D(Collider2D collider){
hsLabel.enabled = true;
restartScreen.SetActive (true);
}

But that doesn’t work. Are there something that I wrongly put?

thank you

3 Likes

Text derives form MonoBehavior so access the GameObject so you can just turn off and on the gameObject using text.gameObject.SetActive(boolean)

11 Likes

wow, worked wonderfully! thanks!

1 Like

thank you!!

But what if you wanted to keep using the script ?

Put that this script on canvas and use buttons to Hide or show any gameobject you want
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hideandshow : MonoBehaviour
{
public void showchat(GameObject obj)
{
obj.SetActive(true);
}
public void hidechat(GameObject obj)
{
obj.SetActive(false);
}
}