Author Topic: Changing Font at runtime  (Read 4430 times)

Tripwire

  • Full Member
  • ***
  • Thank You
  • -Given: 9
  • -Receive: 0
  • Posts: 163
    • View Profile
Changing Font at runtime
« on: January 23, 2013, 05:08:23 AM »
HI,

I'm having a problem with changing the font at runtime. I have a bold orange font and a white light font which need to be changed at runtime on a click event. What i have now:
  1. public var orangeBoldFont : UIFont;
  2. public var whiteLightFont : UITFont;
  3.  
  4. private var tabFont : UILabel;
  5.  
  6. function Awake()
  7. {
  8.     tabFont = GameObject.Find("Tab01").GetComponent(UILabel);
  9.     tabFont.font = whiteLightFont;
  10. }
  11.  
  12. function OnClick()
  13. {
  14.     tabFont.font = OrangeBoldFont;
  15. }
  16.  

Now this works but only for a moment and it changes back to the original whiteLightFont :(

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: Changing Font at runtime
« Reply #1 on: January 23, 2013, 08:41:39 AM »
GameObject.Find is a really bad idea in general, and is not guaranteed to work in Awake. Start() is a better option if you must use it, but I recommend making a public var myLabel : UILabel instead. You can then set it in the inspector via drag & drop.

That said, I don't see why it would change back to white font. Perhaps you're changing it elsewhere?

Tripwire

  • Full Member
  • ***
  • Thank You
  • -Given: 9
  • -Receive: 0
  • Posts: 163
    • View Profile
Re: Changing Font at runtime
« Reply #2 on: January 23, 2013, 08:56:50 AM »
GameObject.Find is a really bad idea in general, and is not guaranteed to work in Awake. Start() is a better option if you must use it, but I recommend making a public var myLabel : UILabel instead. You can then set it in the inspector via drag & drop.

That said, I don't see why it would change back to white font. Perhaps you're changing it elsewhere?

Thx for your reply! I fixed the problem, made a typo somewhere ^^. No i have another question, i've always used Awake() to find stuff and never had problems with it. Why is it bad to use GameObject.Find() in Awake() function? I thought Awake and Start where both called once but Awake is called first?

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: Changing Font at runtime
« Reply #3 on: January 23, 2013, 11:09:20 AM »
Awake is called right after the object's constructor, and can be called prior to you setting up the parent and other stuff.

Consider this:
  1. GameObject go = new GameObject("Test");
  2. CustomScript cs = go.AddComponent<CustomScript>();
  3. cs.targetLabel = myLabel;
The CustomScript's Awake() function will be called prior to cs.targetLabel being set.