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 *!= gameObject){ //Keep from adding self to list*
-
CharacterAffinity tempAffinity;*
tempAffinity = new CharacterAffinity(characterList_.GetComponent().CharacterID,characterList*,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 assuming characterList*.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.
– VesuvianPrimeOne 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.
– FanttumI checked each of the individual values in the tempAffinity line and they're all working properly, and debug.logs show that characterList*.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.*
– Sendatsu_Yoshimitsu