Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Instancing Text Prefab - getting NullReferenceException

Discussion in 'Scripting' started by dmennenoh, Feb 2, 2016.

  1. dmennenoh

    dmennenoh

    Joined:
    Jul 1, 2015
    Posts:
    379
    In my manager script I have a public variable damageTextPrefab that has a reference to a text prefab I made. I also have a public var with a reference to the Canvas.

    I do this:
    Text textBox = Instantiate(damageTextPrefab, nPos, transform.rotation) as Text;
    textBox.transform.SetParent(renderCanvas.transform, false);

    And I get a nullReferenceException in the SetParent line. Not sure what I'm doing wrong.
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,744
    Your problem is 'as Text'. Instantiate returns a GameObject. When you try to cast it to a Text, it can't - since you're using the 'as Text' method of casting (as opposed to (Text)Instantiate...), it simply returns null when it can't perform the cast.

    Cast it to GameObject instead, then use GetComponent if you need the Text component.
     
  3. dmennenoh

    dmennenoh

    Joined:
    Jul 1, 2015
    Posts:
    379
    Perfect. Thank you. I had copy/pasted that code from an example I found. I wonder - in a previous version would that have worked? The cast to Text I mean. I find a lot of helpful Unity examples but have found many times where it's for older versions.
     
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,744
    Nope, that never worked. Whoever wrote that example was off their rocker.
     
  5. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    It's also worth mentioning that there's a generic overload of Instantiate now
     
  6. A.Killingbeck

    A.Killingbeck

    Joined:
    Feb 21, 2014
    Posts:
    483
    Of course it did. As long as the Object passed into the Instantiate function was of the same type you were trying to cast to. Infact, you wouldn't even need the 'as Text' cast if it was as follows:

    Code (CSharp):
    1.  
    2.  
    3. public class FooClass
    4. {
    5.    public Text m_textPrefab;
    6.  
    7.    void Foo()
    8.   {
    9.    Text myText = Instantiate(m_textPrefab);
    10.   }
    11.  
    12. }