- Home /
NullReferenceException, I don't understand why.
Ok so I'm trying to add attributes that change the characters statistics. I have the character page where the attributes are displayed, I'm trying to change some text so its says how many points are in the attribute but I keep getting the null reference exception error when I have already called it.
void SetAttributes () {
Attributes attribs = GetComponent<Attributes> ();
if (isVit == true)
GetComponent<TextMesh> ().text = attribs.vitality.ToString ();
vitality is just a public int at the top of a class on another script set to 5.
Is the 'Attributes' component on the same game object as this script? If not, you will get a null reference exception.
Ahh I see, no its not, is there a way that I don't have to put it on anything, I just want it to store the numbers of the attributes so it can be accessed by other scripts to work out things like the maximum health, and on this script so the player can add more points into them.
Put: Attributes attributes; at the top of your class and initialize it in the start function with: attributes = new Attributes ().
If you are trying to reference it from another object, you should reference the object first and then the component.
attributes = GameObject.Find("ObjectWithAttributes").GetComponent();
So basically I have to put it on an object then? I suppose the best object would be the character then even though thats in a different scene, or would that not work?
Answer by Danteeva · Feb 07, 2014 at 09:51 PM
Right the Dontdestroyonload wasn't working for me, in the end I took out mono behaviour from the attributes script and made the variables static and called the like this
Attributes.vitality
very simple, probably why nobody said it :S I got it from this link here if someone else needs it: http://flashpot.wordpress.com/2013/05/16/how-to-pass-data-between-scenes-static-variables/
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
NullReferenceException error in an array of objects 0 Answers
Can't find source of trigger Null Reference Exception 1 Answer
Accessing RigidbodyFirstPersonController 0 Answers