- Home /
Event throwing null reference exception in OnTriggerEnter
I'm trying to create a means so that when something in my game takes damage, it can notify any other scripts that need to know - I'm doing this by means of an event, which the other scripts hook up to:
using UnityEngine;
using System;
namespace Common
{
public class DamageCollisionListener : MonoBehaviour
{
public event Action<Transform> TriggerEntryEvent;
public void OnTriggerEnter(Collider collidedWith)
{
if (collidedWith.tag == GlobalConstants.Damage_Collider_Tag)
{
Debug.Log(collidedWith.name + " was hit, fire event (I am " + transform.name + ")");
TriggerEntryEvent.Invoke(collidedWith.transform);
}
}
}
}
One of the classes that hook up to this is meant to update a "state" value when a hit is taken (this is currently part-finished, I'm trying to test the event hook-up):
using UnityEngine;
using Common;
using Characters.Shared.Foundation.Interfaces;
namespace Characters.Shared.StateUpdateTriggers
{
public class TakeHitStateTrigger : IStateUpdateTrigger
{
private DamageCollisionListener _damageListener;
private Transform _characterTransform;
public TakeHitStateTrigger(DamageCollisionListener damageListener, Transform characterTransform)
{
_characterTransform = characterTransform;
_damageListener = damageListener;
_damageListener.TriggerEntryEvent += HandleTriggerEntryEvent;
}
private void HandleTriggerEntryEvent(Transform hitByTransform)
{
Debug.Log("HIT");
}
public CharacterState HandleStateUpdate(CharacterState state)
{
return state;
}
}
}
... but instead of the expected "HIT" being logged in the console when the trigger collision fires, I am getting a null reference exception.
I have tested this quite exhaustively: I added in a bit of functionality to force the event to be invoked directly after wire-up in the TakeHitStateTrigger - the event fired perfectly. I then tried adding the same forced invocation in the TakeHitStateTrigger.HandleStateUpdate method (which is called every update) - again, the event fires as expected. It is just when the actual OnTriggerEnter occurs that the event fails.
Any ideas would be useful - this is driving me nuts!
Thanks!
Your answer
![](https://koobas.hobune.stream/wayback/20220612113452im_/https://answers.unity.com/themes/thub/images/avi.jpg)