Search Unity

Access Button's Text when Button is part of a prefab

Discussion in 'UGUI & TextMesh Pro' started by rainbowegg, Sep 10, 2014.

  1. rainbowegg

    rainbowegg

    Joined:
    May 6, 2014
    Posts:
    12
    Hi everyone! I'm having a weird problem and I don't know if it's me or Unity.

    I have a prefab that has a button as a child. I want to be able to change the text on the button via code. However, "button.text" does not seem to be an option. I can do "button.guiText", but when I run it, Unity says that the guiText doesn't exist. I never used the old UI but I think that was the old name for the text/label component.

    Here's what I'm doing right now:

    Code (CSharp):
    1.     public void SetHireHeroPrefab(Hero heroInfo) {
    2.  
    3.         Text buttonText = hireHeroButton.GetComponent<Text>();
    4.         buttonText.text = string.Format("$1000");
    5.  
    6.         ...
    7.     }
    But I get the "Type IPointerClickHandler expected Button received. i:0. Object reference not set to an instance of an object" error (I know this is fixed, I just haven't updated yet) because buttonText is null when I try to access it. What am I doing wrong?

    Note: I am using UnityEngine.UI;

    Thanks!
     
  2. JAKJ

    JAKJ

    Joined:
    Aug 17, 2014
    Posts:
    185
    When you try to change the text property of the Text component, it also tries to use the layout system to mark things as dirty for rebuild and other such bookkeeping. So stop trying to alter your prefabs, and just set the text after you instantiate the button instead of before.
     
  3. rainbowegg

    rainbowegg

    Joined:
    May 6, 2014
    Posts:
    12
    Thanks for your response! Actually the problem was that the text is a child, not a component. Dumb mistake on my part.