- Home /
Null reference exception - singletone
I get a "NullReferenceException: Object reference not set to an instance of an object" In this line:
void Update() { livesRemaining.text = "Something"; }
'livesRemaining is a GUIText which was previously assigned through unity editor (There was no problem): public GUIText livesRemaining;
I changed my class into a singleton, and now I get the message. I get the GUIText through GameObject.Find(), like this:
void Start() { livesRemaining = GameObject.Find("LivesRemaining").GetComponent(); }
Here is the declaration of the class:
public class GameLogic : MonoBehaviour {
private static GameLogic _instance;
public static GameLogic Instance
{
get
{
if (null == _instance)
{
GameObject go = new GameObject("GameLogic");
_instance = (GameLogic)go.AddComponent(typeof(GameLogic));
}
return _instance;
}
}
}
This solves the problem:
try
{
livesRemaining.text = "Lives Remaining: " + livesAmount.ToString();
}
catch
{
print(" Error occured");
}
Can someone give me a hint what is the problem?
Many thanks in advance, vond2
Edit:
Problem solved by moving all the code into Start() instead of Awake()...
If you solved your problem why not create a new answer with what you did and mark it as the correct one? Or at least close the question.
Your answer
![](https://koobas.hobune.stream/wayback/20220613005858im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Manually creating Editor sometimes leads to NullReferenceException in SerializedObject constructor 0 Answers
Distribute terrain in zones 3 Answers
List Set in Editor no longer contains Items after Transplant to new Level (pooler = singleton) 0 Answers
Need a hand using array.Length in a C# editor script 1 Answer