NullReference exception on gameObject.AddComponent<>()

I am trying to add a “NPCNeed” component to an NPC gameobject.

Because I cannot use constructors, I have an Init method on my base Need class

abstract Need : Monobehaviour

NPCNeed : Need

I have an NPCNeedFactory class responsible for creating and attaching all the different Needs to the NPC.gameObject that calls it.

However when I state:

//Attaches a new Empty NPCNeed to character (passed through in method sig)
NPCNeed charNeed = character.gameObject.AddComponent<NPCNeed>();

//This does not throw an exception
Debug.Log(charNeed);

//Init fills out the variables for NPCNeed
charNeed.Init(  //NullReference throw here: Object reference not set to an instance of an object
    j["NPCNeed"]*["needName"].Value,* 

NeedStatusFactory(j),
j[“NPCNeed”][“startingValue”].AsInt,
j[“NPCNeed”][“valueDecrementRate”].AsInt,
j[“NPCNeed”][“timeToDecrement”].AsInt //Code doesn’t get here, these just pull vars from a JSON script
);
I can post more code if needed, but I want to believe that I’m missing something obvious. Why hasn’t charNeed become the object reference Init() is looking for?

Have you debugged your code? I mean with a breakpoint.

I guess that charNeed isn’t null, the whole call to the “Init” method is the problem and it is 1 “line”, try getting all those values outside the Init call on separate variables. One of them should throw the NullPointerException before reaching the charNeed.Init line.

Note that any of this steps could return a null pointer:

j["NPCNeed"]
j["NPCNeed"]

j[“NPCNeed”][“needName”]
j[“NPCNeed”][“startingValue”]
j[“NPCNeed”][“valueDecrementRate”]
j[“NPCNeed”][“timeToDecrement”]
Even “j” can be null there.

You are getting nullrefrence cause charNeed is null. Debug will also write “null”.

Try this: NPCNeed charNeed = character.gameObject.AddComponent(NPCNeed);