- Home /
Public class used in another class (C#)
Ok, i have a sort-of advanced problem, which i'm sure has a simple solution, but i just can't manage to find it...
Let's say i have a public class, designed to be editable from the inspector...
[System.Serializable]
public class PersonType {
string gender;
bool schoolEmployee;
GameObject model;
}
...and i use this class in another class, which i assign to a gameobject, where i set several instances of it (everything filled in inspector)...
public class PeopleTypes : MonoBehaviour {
public PersonData maleStudent;
public PersonData femaleStudent;
public PersonData Teacher;
public PersonData Janitor;
}
...and i use the PersonType class as a part of another class (Person type defining the type of a person, Individual defining the individual parameters)...
public class Individual : MonoBehaviour {
string name;
int age;
PersonType pType;
}
...why do i get a nullreference exception when i try to set...
Individual ind_1 = new Individual();
ind_1.pType = PeopleTypes.maleStudent; //<- this is where i get the error
...or better yet, what would be the correct way of setting this? I guess a part of the problem would be whether this is the correct way to set up a public class for inspector editing...
You can turn those into structs if all they're gonna be are storage/placeholders.
I think custom structs aren't serialized in the Inspector.
I don't understand your code... What is PersonData? Is it PersonType? Why do you access to maleStudent like a static member of PeopleTypes? From where do you call the GetComponent?
Yeah, sry, PersonData should be PersonType. I was simplyfying an example. Anyway, the problem is solved. Tnx for help :)
Answer by GuyTidhar · Jun 28, 2011 at 07:18 PM
You must not use new to instantiate MonoBehaviour classes. Instead, you should instantiate components or game objects or don't inherit from MonoBehaviour when you want to use "new".
If you don't need your class to have its own update, coroutine and the general Unity processing functionality, just use the classes you wrote without inheriting (or inheriting from non mono base class).
http://unity3d.com/support/documentation/ScriptReference/index.Instantiate.html
Having removed the $$anonymous$$onoBehaviour from the class 'Individual' there is 1 less warning, but no change in functionality - the error is still there.
It might be of some value to note, that peopleType from peopleType.malestudent in the example above is received by 'PeopleTypes peopleType = GetComponent("PeopleTypes") as PeopleTypes;
Tnx for the help so far :)
It's called in the Awake routine. It is then used in the same routine further down. Both scripts (PeopleTypes and the script that calls it) are on the same game object....wait a second...GAH! There was a typo in the GetComponent parameter string....boy is my face red
Well it works now (i knew it was something dumb), i was taking the GetComponent part for granted and failed to double check :P
Tnx for everyones help!