I’m currently going through the Unity Junior Developer pathway and I’m debugging an app. I can’t for the life of me figure out why there is an issue with the list.
Error:
NullReferenceException: Object reference not set to an instance of an object
CongratScript.Start () (at Assets/CongratScript.cs:25)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CongratScript : MonoBehaviour
{
public TextMesh Text;
public ParticleSystem SparksParticles;
private List<string> TextToDisplay;
private float RotatingSpeed;
private float TimeToNextText;
private int CurrentText;
// Start is called before the first frame update
void Start()
{
TimeToNextText = 0.0f;
CurrentText = 0;
RotatingSpeed = 1.0f;
TextToDisplay.Add("Congratulation");
TextToDisplay.Add("All Errors Fixed");
Text.text = TextToDisplay[0];
SparksParticles.Play();
}
// Update is called once per frame
void Update()
{
TimeToNextText += Time.deltaTime;
if (TimeToNextText > 1.5f)
{
TimeToNextText = 0.0f;
CurrentText++;
if (CurrentText >= TextToDisplay.Count)
{
CurrentText = 0;
Text.text = TextToDisplay[CurrentText];
}
}
}
}
There is more but I’m doing the best I can to be independant on this. Any help would be much appreciated.
You never assigned a value to your List variable. Since List is what’s known as a “reference type” (as all classes in C# are), a variable of type List is actually just like a signpost that can point to a List instance. However, the signpost is always initially pointing to nothing. If you try to call a method on a reference that refers to nothing (null), you get a NullReferenceException.
The solution is to point your reference at an actual instance of type List. To do this, you can create a new List object with a call to the constructor for List:
private List<string> TextToDisplay = new List<string>();
Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.
This is the kind of mindset and thinking process you need to bring to this problem: