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. Dismiss Notice

Object reference not set to an instance of an object

Discussion in 'Scripting' started by angelojosedarosa01, Nov 30, 2020.

  1. angelojosedarosa01

    angelojosedarosa01

    Joined:
    Nov 30, 2020
    Posts:
    2
    I was following this tutorial about how to do a HighScore:
    and i have this error in my unity, so i decide to copy exactly like him, and I have the same error, I searched in some foruns what does that error means and I get confused. Can someone tell me what is wrong please?

    Code (CSharp):
    1. NullReferenceException: Object reference not set to an instance of an object
    2. HighScoreScript.SetScore (System.String scoreName, System.String score, System.String rank) (at Assets/Scripts/HighScoreScript.cs:15)
    3. HighScoreManager.ShowScores () (at Assets/Scripts/HighScoreManager.cs:88)
    4. HighScoreManager.Start () (at Assets/Scripts/HighScoreManager.cs:22)
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class HighScoreScript : MonoBehaviour
    7. {
    8.     // Start is called before the first frame update
    9.     public GameObject score;
    10.     public GameObject scoreName;
    11.     public GameObject rank;
    12.  
    13.     public void SetScore(string score, string name, string rank)
    14.     {
    15.         this.score.GetComponent<Text>().text = score;
    16.         this.scoreName.GetComponent<Text>().text = name;
    17.         this.rank.GetComponent<Text>().text = rank;
    18.     }
    19. }

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System;
    5. using System.Data;
    6. using Mono.Data.Sqlite;
    7.  
    8. public class HighScoreManager : MonoBehaviour
    9. {
    10.  
    11.     private string connectionString;
    12.     private List<HighScore> highScores = new List<HighScore>();
    13.     public GameObject scorePrefab;
    14.     public Transform scoreParent;
    15.     // Start is called before the first frame update
    16.     void Start()
    17.     {
    18.         connectionString = "URI=file:" +Application.dataPath + "/HighScoreDB.db";
    19.         // InsertScore("muriel",99);
    20.         //DeleteScore(2);
    21.  
    22.         ShowScores();
    23.         //GetScores();
    24.     }
    25.  
    26.     // Update is called once per frame
    27.     void Update()
    28.     {
    29.        
    30.     }
    31.  
    32.     private void InsertScore(string name, int newScore) {
    33.          using (IDbConnection dbConnection = new SqliteConnection(connectionString)){
    34.             dbConnection.Open();
    35.             using (IDbCommand dbCmd = dbConnection.CreateCommand())
    36.             {
    37.                 string sqlQuery = String.Format("INSERT INTO HighScores(Name, Score) VALUES(\"{0}\",\"{1}\")",name, newScore);
    38.                 dbCmd.CommandText = sqlQuery;
    39.                 dbCmd.ExecuteScalar();
    40.                 dbConnection.Close();
    41.             }
    42.         }
    43.     }
    44.    
    45.     private void GetScores()
    46.     {
    47.         highScores.Clear();
    48.         using (IDbConnection dbConnection = new SqliteConnection(connectionString)){
    49.             dbConnection.Open();
    50.             using (IDbCommand dbCmd = dbConnection.CreateCommand())
    51.             {
    52.                 string sqlQuery = "SELECT * FROM HighScores";
    53.                 dbCmd.CommandText = sqlQuery;
    54.                 using(IDataReader reader = dbCmd.ExecuteReader()) {
    55.                     while (reader.Read())
    56.                     {
    57.                         //Debug.Log(reader.GetString(1) + " - " + reader.GetInt32(2));
    58.                         highScores.Add(new HighScore(reader.GetInt32(0),reader.GetInt32(2),reader.GetString(1),reader.GetDateTime(3)));
    59.                     }
    60.                     dbConnection.Close();
    61.                     reader.Close();
    62.                 }
    63.             }
    64.         }
    65.     }
    66.         private void DeleteScore(int playerID) {
    67.                  using (IDbConnection dbConnection = new SqliteConnection(connectionString)){
    68.             dbConnection.Open();
    69.             using (IDbCommand dbCmd = dbConnection.CreateCommand())
    70.             {
    71.                 //string sqlQuery = String.Format("INSERT INTO HighScores(Name, Score) VALUES(\"{0}\",\"{1}\")",name, newScore);
    72.                 string sqlQuery = String.Format("DELETE FROM HighScores WHERE PlayerID = \"{0}\"",playerID);
    73.                 dbCmd.CommandText = sqlQuery;
    74.                 dbCmd.ExecuteScalar();
    75.                 dbConnection.Close();
    76.             }
    77.         }
    78.     }
    79.     private void ShowScores()
    80.     {
    81.         GetScores();
    82.         for (int i = 0; i < highScores.Count; i++)
    83.         {
    84.                 GameObject tmpObject = Instantiate(scorePrefab);
    85.  
    86.                 HighScore tmpScore = highScores[i];
    87.  
    88.                 tmpObject.GetComponent<HighScoreScript>().SetScore(tmpScore?.Name, tmpScore?.Score.ToString(), "#" + (i + 1).ToString());
    89.                 tmpObject.transform.SetParent(scoreParent);
    90.  
    91.                 tmpObject.GetComponent<RectTransform>().localScale = new Vector3(1, 1, 1);
    92.         }
    93.     }
    94. }
     

    Attached Files:

  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,144
    It's a null error. It means that either the variable "score" has no value (you probably failed to drag and drop) or you don't have the Text component on the "score" gameobject. Get use to this error, you'll probably see it a lot.
     
  3. Ray_Sovranti

    Ray_Sovranti

    Joined:
    Oct 28, 2020
    Posts:
    172
    NullReferenceException means that you've tried to "dig in" to a variable that is null. That is to say, you have a dot on the line, and the thing on the left of that dot is null. Looking at the line the exception happens on:
    Code (csharp):
    1.         this.score.GetComponent<Text>().text = score;
    There are three dots, so look to the left of each of them to see if that could be the culprit.
    First dot: "this" is pretty much never going to be null; "this" means "the object this code is running on" and if it were null, the code would probably not be running. (It's also usually unnecessary, because it's implied; you usually only need "this" to distinguish between a class variable and a local variable of the same name, which is usually not good practice anyway, except for in constructors... but I'm getting offtopic)

    Second dot: Could "score" be null? yes, it definitely could, if you haven't assigned that reference in the inspector.

    Third dot: Could "GetComponent<Text>()" be null? Yes, if the object being referenced doesn't have a Text component attached.

    So basically, the issue here is either with the property being assigned, or the object not having an attached Text component.
     
  4. angelojosedarosa01

    angelojosedarosa01

    Joined:
    Nov 30, 2020
    Posts:
    2
    thank you all, the error is because I'd was using a textmeshpro instead of using a text, and because of this the unity wasnt recognizing the tmp.
     
  5. malcomjarr

    malcomjarr

    Joined:
    Nov 18, 2020
    Posts:
    7
    An Object is an instance of a Class , it is stored some where in memory. A reference is what is used to describe the pointer to the memory location where the Object resides. The message "object reference not set to an instance of an object" means that you are referring to an object the does not exist or was deleted or cleaned up. It's usually better to avoid a NullReferenceException than to handle it after it occurs. To prevent the error, objects that could be null should be tested for null before being used.

    if (mClass != null)
    {
    // Go ahead and use mClass
    mClass.property = ...
    }
    else
    {
    // Attempting to use mClass here will result in NullReferenceException
    }