kybo10 kybo10 - 12 days ago 6
C# Question

NullReferenceException: Object reference not set to an instance of an object - unity

I am following a tutorial on youtube trying to make a clicker game, getting this error:

NullReferenceException: Object reference not set to an instance of an object
Click.Update () (at Assets/Scripts/Click.cs:13)
I have followed the code word for word that he typed, but no dice. I read that it means my instance = null, but if it = null shouldnt the instance be = this because of the CreateInstance() method?

Currency Converter.cs:

using UnityEngine;
using System.Collections;

public class CurrencyConverter : MonoBehaviour
{
private static CurrencyConverter instance;
public static CurrencyConverter Instance
{
get
{
return instance;
}
}

private void Awake()
{
CreateInstance();
}

void CreateInstance()
{
if (instance == null)
{
instance = this;
}
}

public string GetCurrencyIntoString(float valueToConvert, bool currencyPerSec, bool currencyPerClick)
{
string converted;

if (valueToConvert >= 1000000)
{
converted = (valueToConvert / 1000000f).ToString("f3") + " Mil";
}
else if (valueToConvert >= 1000)
{
converted = (valueToConvert / 1000f).ToString("f3") + " K";
}
else
{
converted = "" + valueToConvert;
}

if(currencyPerSec == true)
{
converted = converted + " gps";
}

if(currencyPerClick == true)
{
converted = converted + " gpc";
}
return converted;
}
}


Click (Basically game manager):

using UnityEngine;
using System.Collections;

public class Click : MonoBehaviour {

public UnityEngine.UI.Text gpc;
public UnityEngine.UI.Text goldDisplay;
public float gold = 0;
public int goldPerClick = 1;

private void Update()
{
goldDisplay.text = "Gold: " + CurrencyConverter.Instance.GetCurrencyIntoString(gold, false, false);
gpc.text = goldPerClick + " Gold/Click";

}

public void Clicked()
{
gold += goldPerClick;

}

}

Answer

Check that you've assigned the two UI elements in the inspector on the GameObject with the Click behaviour.