- Home /
NullReferenceException: on Static variables
Hi, Can please some one help me? I'm trying something i saw in Unity Live training but is not working in my script and i cant find why.
this is Script1:
using UnityEngine;
using System.Collections;
public class TesrMor : MonoBehaviour {
public static TesrMor tM;
public int n = 5;
public bool mn=false;
void Update()
{
Debug.Log(n);
}
}
and this script2
using UnityEngine;
using System.Collections;
public class testget : MonoBehaviour {
int u=20;
bool q=true;
// Use this for initialization
void Start ()
{
u = TesrMor.tM.n;
}
// Update is called once per frame
void Update ()
{
q=TesrMor.tM.mn;
}
}
all the time give me this error : NullReferenceException: Object reference not set to an instance of an object testget.Start () (at Assets/Scripts/Player/testget.cs:11) and NullReferenceException: Object reference not set to an instance of an object testget.Update () (at Assets/Scripts/Player/testget.cs:17)
Can some one help me ??
You're not setting any value for that variable.
You'll need to initialize it or to drag a gameobject to the variable field on inspector.
This is what i want to do. but is not working
Answer by nicolasjr · Apr 14, 2014 at 05:34 PM
In order to do a Singleton, you need some extra code:
public class TesrMor : MonoBehaviour {
TesrMor() { }
public static TesrMor tM
{
get
{
if(_tM == null)
{
_tM = new TesrMor();
}
return _tM;
}
}
public int n = 5;
public bool mn=false;
private static TesrMor _tM;
void Update()
{
Debug.Log(n);
}
}
Let me know if it worked!
oh, by the way, you'll need to set the private pointer to the class itself once you initialize it!
void Start()
{
_t$$anonymous$$ = this;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613142711im_/https://answers.unity.com/themes/thub/images/avi.jpg)