- Home /
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 :(
Thanks in advance!
Frederik
Answer by mas · Sep 01, 2013 at 01:24 PM
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.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Yet another null reference exception 1 Answer
i can see my objects collide but OnCollisionEnter never called c# 1 Answer