Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

can't cast GameObject to Text

Discussion in 'Scripting' started by steveh2112, Jan 17, 2020.

  1. steveh2112

    steveh2112

    Joined:
    Aug 30, 2015
    Posts:
    314
    this should be easy but why can't i do this?
    Code (CSharp):
    1. public GameObject _EditModePanel;
    2.     Text _NameText;
    3.  
    4.     private void Start()
    5.     {
    6.         GameObject go = Helpers.GetChildGameObject(_EditModePanel, "NameText");
    7.         _NameText = (Text)go;
    8.  
    9.     }
    _NameText = (Text)go; says cannot convert type unityengine.gameobject to unityengine.ui.text
    thanks
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,186
    What are you trying to do? Get the gameobject name? Or do you want a Text component off the gameobject?

    Code (CSharp):
    1. _NameText.text = go.name;
    2.  
    3. _NameText = go.GetComponent<Text>();
    4.  
    5.  
    You can't cast a GameObject to a Text. Text is a component on a GameObject. Not the GameObject itself.
     
  3. steveh2112

    steveh2112

    Joined:
    Aug 30, 2015
    Posts:
    314
    oops, my bad, Text is a component of game object so changed GetChildGameObject to transform and did this
    _NameText = Helpers.GetChildGameObject(_EditModePanel, "NameText").GetComponent<Text>();