- Home /
NullReferenceException Error how to solve?
Hello everyone.
I need your help,I don´t know why this error appers, because my game works same with the error. The error is here:
NullReferenceException: Object reference not set to an instance of an object Monetario.Update () (at Assets/Script/Botoes/Monetario.cs:18)
My code is here:
using UnityEngine; using System.Collections; using UnityEngine.UI;
public class Monetario : MonoBehaviour {
public static int coins = 0;
public UnityEngine.UI.Text moneytxt;
// Use this for initialization
void Start () {
//Guarda o money
coins = PlayerPrefs.GetInt("coins");
}
// Update is called once per frame
void Update () {
coins = PlayerPrefs.GetInt("coins");
moneytxt.text = "Coins: " + coins.ToString();
}
}
Thank you very much
Above script works fine,the only thing u have missed is to assign the UI text to moneytxt.
thank you, i don´t drag and drop the text component, because of this the error appear.
Answer by dhivakar · Jul 17, 2015 at 08:58 AM
Hi, You have the moneytext to be a public variable that holds UI.Text. Have you assigned the object for this variable in the editor.
If you are manually creating the object then check if you have instantiated the object.
Attach the process to unity and put a break point in the update and check if the money is not null. Else simply you can assign the value to the moneytext.text only if the value is not null like this
void Update () { coins = PlayerPrefs.GetInt("coins"); if(moneytxt != null) moneytxt.text = "Coins: " + coins.ToString(); }
Thanks,i did this changes in the code, now the is better. And the error it´s because i don´t drag and drop the text element to the inspector.
Answer by alok-kr-029 · Jul 17, 2015 at 04:30 AM
the script seem to be find one thing I would like to correct is you can directly use
public Text moneytxt;
and you have to drag and drop the "Text " in inspector as it is not getting the text and it is giving null value .
hope this will solve your problem
Thank you very much, the problem is in the inspector i don´t drag and drop the "Text" like you said. Thanks for your help.
Your answer
Follow this Question
Related Questions
My player figure falls down after load 1 Answer
Lots of "semantic issues" causing build to fail? 0 Answers
`System.IO.File' does not contain a definition for `ReadAllBytes'? 1 Answer
does the difference of Unity 5 pro and Unity(not pro) might be the reason why Im getting an error? 1 Answer
White Screen Editor 5.5.2f 2 Answers