- Home /
NullReferenceException even though I assigned it?
Hi, I'm a newbie when it comes to Unity, so forgive me if the answer to this is brutally obvious.
I'm making a Gravity controller using the following code:
In a script called GlobalPhysics, where I store all the global variables, I have a float variable. called Gravity. I declared it as " public float Gravity = 9.8f;".
In a separate test script attached to the game object I want to manipulate, I put in this line to put the gravity in effect:
public Rigidbody rbTest;
private GlobalPhysics globalPhysics;
void FixedUpdate()
{
rbTest.AddForce(Vector3.down * globalPhysics.Gravity * rbTest.mass);
}
However, when I go and run the script, it keeps throwing the error "NullReferenceException : Object reference not set to an instance of an object". I've looked at several questions and answers and I haven't been able to find much. How do I fix this?
Answer by cjdev · Sep 28, 2015 at 07:50 AM
The problem you have is that you are declaring the globalPhysics variable of type GlobalPhysics (your script) but you aren't actually creating a GlobalPhysics object to store in that variable. Normally you'd need to do something like this:
void Start() {
globalPhysics = new GlobalPhysics();
}
That way you have an object that you can use to get the variable Gravity it contains. However, if you are looking to make a class purely of global variables I would definitely recommend using a static class. What this means is that you don't need to make an object like this in order to access the variables and functions of the class, which makes it work well with constants and global variables. To make a static class you'd do something like this:
public static class GlobalPhysics {
public static float gravity = 9.81f;
}
And then you could call it in your script like this:
rbTest.AddForce(Vector3.down * GlobalPhysics.gravity * rbTest.mass);
Notice that there's no instantiating or new variables required, which makes it a lot more flexible.
@cjdev I am having the same issue and creating a new object actually makes things worse. In addition to the NullReferenceException now I get a warning that says "you are trying to create a $$anonymous$$onoBehaviour using the 'new' keyword. This is not allowed. $$anonymous$$onoBehaviours can only be added using AddComponent()." What am I doing wrong?