OnTriggerEnter - null reference?

Hey, I have a projectile with this code:

    function OnTriggerEnter(other : Collider) {
print("gonna shoot everything");
		if (other.gameObject.tag == "Enemy")
			{
			print("ENEMENEMENEMY");
	var hlth : Health;
	hlth = other.gameObject.GetComponent(Health);
	hlth.DoDamage(damage);

}
}

it prints both fine. The problem is, when the projectile collides with the enemy (box collider w/ rigidbody that is trigger) it brings this error to the line with the GetComponent.

NullReferenceException: Object reference not set to an instance of an object
Projectile.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Projectile.js:34)

I’ve tried variations, but all of them return null. What could be causing this?

edit: Any chance this could be a 3.5 collider bug?

OnTrigger events are sent to both, the trigger and the other object. If only one of them has the Health script, the other will generate the NullReferenceException.

Check if hlth isn’t null before using it:

    ...
    var hlth : Health;
    hlth = other.gameObject.GetComponent(Health);
    if (hlth) hlth.DoDamage(damage);
    ...

not sure but you can try:

    function OnTriggerEnter(other : Collider) {
print("gonna shoot everything");
       if (other.gameObject.tag == "Enemy")
         {
         print("ENEMENEMENEMY");
    var hlth : Health;
    var yourObject : GameObject;
    yourObject = other.gameObject;
    hlth = yourObject.GetComponent(Health);
    hlth.DoDamage(damage);

} 
}

I don’t know if this will help but I had a similar problem and it was giving me a null reference also. It said other : Collider etc but the real issue was in the function i called in the OnTriggerEnter and the function i called was calling out another game object that was being deleted on Start. So the issue wasn’t with the OnTriggerEnter at all.

Be sure to double click the console error and it will bring you to the real issue. I hope this helps.

I also had this problem and I solved it this way:

Is a child with an active collider and with the same tag attached to the object you are checking the OnTriggerEnter for? This might cause the trouble because the OnTriggerEnter function might not know how to deal with the child object.

So if your main object AND the child object both have the tag “Enemy”, the OnTriggerEnter (obviously) fails at finding the script component at the attached child object because the Health function only is placed on the parent object. So the null error message in this case is kind of like: “Hey guy, I cannot find that function on one of your “Enemy” tags, there is no script”.

At least, this was the solution in my case. Maybe this is similar to your problem. :slight_smile:

Check for duplicates of your attached scripts to the game object, or if you used AddComponent() somewhere. This well cause the object to have multiple scripts but only one will run the OnTriggerEnter() and leaves the other with null reference.