Search Unity

show / hide text on UI via script

Discussion in 'Scripting' started by FalconJ, Apr 8, 2015.

  1. FalconJ

    FalconJ

    Joined:
    Mar 12, 2015
    Posts:
    146
    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.

    Code (CSharp):
    1.    
    2. public Text hsLabel;      
    3.  
    4. public GameObject restartScreen;
    5.  
    6. void Start(){
    7. restartScreen.SetActive (false);
    8. hsLabel = GetComponent<Text> ();
    9. hsLabel.enabled = false;
    10. }
    11.  
    12. void OnTriggerEnter2D(Collider2D collider){
    13. hsLabel.enabled = true;
    14. restartScreen.SetActive (true);
    15. }
    But that doesn't work. Are there something that I wrongly put?

    thank you
     
  2. Polymorphik

    Polymorphik

    Joined:
    Jul 25, 2014
    Posts:
    599
    Text derives form MonoBehavior so access the GameObject so you can just turn off and on the gameObject using text.gameObject.SetActive(boolean)
     
  3. FalconJ

    FalconJ

    Joined:
    Mar 12, 2015
    Posts:
    146
    wow, worked wonderfully! thanks!
     
    providejahwill likes this.
  4. akash_tambe

    akash_tambe

    Joined:
    Sep 15, 2019
    Posts:
    1
    thank you!!
     
  5. TheGodlyDemon

    TheGodlyDemon

    Joined:
    Aug 10, 2020
    Posts:
    1
    But what if you wanted to keep using the script ?
     
  6. usamasajjad39005

    usamasajjad39005

    Joined:
    Mar 24, 2021
    Posts:
    1
    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);
    }
    }