Getting an unexpected Null Reference Exception

Hello,

So after adding the following snippets of code in Player -

[SerializeField] SpecialAbilityConfig specialAbility01;

specialAbility01.AddComponent(gameObject);

and selecting the Power Attack for specialAbility01 under Player in the inspector, on runtime I get the following error:

NullReferenceException: Object reference not set to an instance of an object
RPG.Characters.PowerAttackConfig.AddComponent (UnityEngine.GameObject gameObjectToAttachTo) (at Assets/Characters/SpecialAbilities/PowerAttack/PowerAttackConfig.cs:18)
RPG.Characters.Player.Start () (at Assets/Characters/Player/Player.cs:46)

‘PowerAttackConfig.cs:18’ points to

behaviourComponent.SetPowerAttackConfig(this);

and ‘Player.cs:46’ points to

specialAbility01.AddComponent(gameObject);

This has me scratching my head , any help would be greatly appreciated.

Thanks!

Just to follow up on this, after some debugging it appears that ‘behaviourComponent’ is null, which is what is cause the error.

Now to find why that is…

Hi,

If it is the behaviourComponent that is causing you NullReferenceException error, follow the code back looking for where you declare and subsequently initialise this variable, perhaps in certain circumstances this isn’t happening.

Thanks for the input Rob :slight_smile:

I managed to find the issue, bit of a 'doh! moment. It was this line

 var behaviourComponent = gameObjectToAttachTo.AddComponent<PowerAttackBehaviour>(); 

Turns out I was using ‘GetComponent’ instead of ‘AddComponent’.

1 Like

Well done for finding the issue and resolving it yourself Pavlos, how rewarding is that! :slight_smile:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms