OnCollision using Orthello2D Framework is causing NullReferenceException

Hello everyone!

I have been trying to check the tag of the object my “score object” collides with.
I tried this:

using UnityEngine;
using System.Collections;

public class ScoreUpgrade : MonoBehaviour
{
	
	public int score = 0;
	
	void Start ()
	{
		this.GetComponent<OTSprite> ().onCollision = OnCollision;
	}
	
	public void OnCollision (OTObject owner)
	{
		if (owner.collision.gameObject.tag == "Player") {
			GameObject.FindGameObjectWithTag ("ScriptHolder").GetComponent<Score> ().addScore (score);
			GameObject.Destroy (this.gameObject);
		}
	}
}

But it seems to give me a NullReferenceException:

NullReferenceException: Object reference not set to an instance of an object
ScoreUpgrade.OnCollision (.OTObject owner) (at Assets/Scripts/Gameplay/Upgrades/ScoreUpgrade.cs:16)
OTObject.OnTriggerEnter (UnityEngine.Collider c) (at Assets/Standard Assets/OT/_Base/OTObject.cs:2212)

And i can’t figure out why :frowning:

Thanks in advance!

  • Frederik

Because the error message displays that your OnCollision callback was called from OTObject.OnTriggerEnter, it looks that there was a trigger activation and no collision involved.

If you are working with triggers instead of collisions (width rigidbodies), your owner.collision will be null but your owner.collisionObject should hold the trigger activator object.

You assume that there is an owner.collision object and do not check if that is null, so this is not really safe. So always check the owner.collision and/or owner.collisionObject to be null before accessing child properties on it.