- Home /
NULL object have values
Basicly, i think, this problem can be not a unity one, but it is annoying.
I have a class with two fields, inherited from monoBehaviour as usual
public class Stats : MonoBehaviour
{
public int MaxHp;
public int CurrentHp;
}
and some other character class with method start and code in it
void Start()
{
this.StatsObject = new Stats {MaxHp = 100, CurrentHp = 99};
}
Now third script, which needs access to the StatsClass fields... Well,you should better look to the screenshot. I've been developing on C# for some years, but i can't get how this is possible
Answer by robertbu · Mar 07, 2014 at 12:05 AM
You should not use 'new' with any class that you derive from MonoBehaviour. The classes are expected to be a component of a GameObject, so if you really want one from scratch you can do:
GameObject go = new GameObject();
this.StatsObject = go.AddComponent<Stats>();
From this limited glimpse, I don't see why you need to derive 'Stats' from MonoBehavior. Given what I see, just remove the ': MonoBehaviour' from the class declaration and continue to use the 'new' operator.
Ahh, thanks. I've tried and it (almost) workded. But i still cannot understand, how the fields can be initialized, but the class equals to null
I would assume that you initialized the fields you added, but Unity needs to initialize the remaining $$anonymous$$onoBehaivor fields. It must do this when it is added to a GameObject.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Issues using the 'new' keyword 3 Answers
GUI problems 0 Answers
Move object Horizontally : 2D 2 Answers
buy older version of unity iPhone for making free games on iPhone 1 Answer