Search Unity

Why couldn't I grab the Text component with this (really) simple script?

Discussion in 'Scripting' started by unwitty, Jun 13, 2015.

  1. unwitty

    unwitty

    Joined:
    Jan 18, 2015
    Posts:
    31
    The variable 'timer' returns null.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System.Collections;
    4.  
    5. public Text timer;
    6.  
    7. void Start()
    8. {
    9.    timer = GetComponent<Text>();
    10.  
    11.    if (timer.text == null)
    12.        Debug.LogError("'timer' is NULL!");
    13. }
    See here for the hierarchy: http://i.imgur.com/0jubtBI.png

    What is wrong with this?
     
  2. Crayz

    Crayz

    Joined:
    Mar 17, 2014
    Posts:
    186
    timer.text is the actual displayed text of the Text component. Switch it to
    Code (csharp):
    1. if(timer == null)
    to check if the component reference is found. If you want to check if a string exists, strings are char arrays so you can use timer.text.Length to see how many characters are in the string. If the Length is 0, there's no string. That's how I do it anyways

    Also since the timer component is placed in the Inspector you don't need to grab a reference via code, no need for:
    Code (csharp):
    1. timer = GetComponent<Text>();
     
  3. unwitty

    unwitty

    Joined:
    Jan 18, 2015
    Posts:
    31
    Yep, I thought it'd be something really simple. Thanks for helping out.

    Is there any performance difference in referencing it via the Inspector vs a GameObject.Find (cached of course)?
     
unityunity