- Home /
Constructor giving nullreference error
I'm trying to use a basic class to hold data on each NPC in the scene, and then assign values to said class during character initialization. The data class reads:
public class CharacterAffinity {
public int characterID;
public GameObject characterObject;
public int characterAffinity;
public CharacterAffinity(int charID, GameObject charObject, int charAffinity){
characterID = charID;
characterObject = charObject;
characterAffinity = charAffinity;
}
}
and I call it while iterating through a list of NPCs:
for (int i = 0; i < characterList.Length; i++) { //Build list of all characters and initialize values
if (characterList[i] != gameObject){ //Keep from adding self to list
CharacterAffinity tempAffinity;
tempAffinity = new CharacterAffinity(characterList[i].GetComponent<CharacterSheet>().CharacterID,characterList[i],UnityEngine.Random.Range(0, 50));
affinityList.Add(tempAffinity);
}
}
The code compiles, but it gives me an error for each call to the constructor, "Object reference not set to an instance of an object". Is there an obvious error in my constructor/class syntax that I'm missing?
I'm assu$$anonymous$$g characterList[i].GetComponent() is returning null.
You're doing an awful lot on that one line, try breaking it into multiple, smaller lines for easier readability and debugging.
One of your public variables might not be set in the inspector. If not set there it would need to be set in start() or awake(), unless you call your CharacterAffinity(…) within one of those. Not quite sure, but that's my guess.
I checked each of the individual values in the tempAffinity line and they're all working properly, and debug.logs show that characterList[i].getcomponent is returning a value. If I add [Serializable] above my class declaration the errors go away, but I don't know if that's the fix or a band-aid hiding a bigger problem.
Answer by Paulius-Liekis · Sep 15, 2014 at 08:55 AM
Why do you think it's the constructor? I would guess it's more likely to be on this line:
characterList[i].GetComponent<CharacterSheet>().CharacterID
I'm reasonably half-certain the problem isn't on that line, simply because swapping out dummy/filler values to guarantee that it isn't getting a null value doesn't eli$$anonymous$$ate the error.
So I did some further testing, if the class is serializeable it works fine, if I remove [serializable] from the class declaration it can't find CharacterID, and returns 0. When I mark as serializable, however, it finds and returns the correct value.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How to make costume classes Visible in the Inspector 3 Answers
Problem with getting a value from a enum 2 Answers