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

Null referenace issue

Discussion in 'Scripting' started by spearbeard, Jan 20, 2019.

  1. spearbeard

    spearbeard

    Joined:
    May 6, 2018
    Posts:
    24
    I am having problem understanding what is wrong with my scripts. they are assinged to the text objects in the project. (collectible counter) I have one of them working being the score. so that for each item collided wiht it goes up by 10. The score goes up by the collison the object gets destroyed. But the other counters do nothing yet have the scirpts on them.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class DiamondCounter : MonoBehaviour
    7. {
    8.  
    9.     public static int diamondsCollected;
    10.     Text text;
    11.  
    12.     void start()
    13.     {
    14.         text = GetComponent<Text> ();
    15.         diamondsCollected = 0;
    16.  
    17.     }
    18.  
    19.     void Update    ()
    20.     {
    21.         text.text = "Diamonds: " + diamondsCollected;
    22.  
    23.     }
    24.  
    25. }
    26.  
    the editor keeps saying theres an error with this line.
    text.text = "Diamonds: " + diamondsCollected;

    the working score part is this code

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class ScoreController : MonoBehaviour {
    7.  
    8.     public static int score;
    9.     Text text;
    10.  
    11.  
    12.  
    13.     // Use this for initialization
    14.     void Start ()
    15.     {
    16.     text = GetComponent<Text> ();  
    17.     score = 0;
    18.  
    19.     }
    20.    
    21.     // Update is called once per frame
    22.     void Update ()
    23.     {
    24.         text.text = "Score: " + score;  
    25.     }
    26. }
    27.  
     
  2. nat42

    nat42

    Joined:
    Jun 10, 2017
    Posts:
    353
    In the first code the start() method begins with a lowercase letter and is likely not being called. I presume that without this the text property is null, hence when you try and access the text.text property you get a null reference because you can't access properties of null
     
  3. spearbeard

    spearbeard

    Joined:
    May 6, 2018
    Posts:
    24
    Thanks turns out it was a quick fix had been going throught the code and must have overlooked it. Yes it was the start methods S.