- Home /
Adding and removing specific components to a list based OnTriggerEnter/Exit, Getting Null Exceptions
Here's the code in question:
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.GetComponentInParent<Room>())
{
r = other.gameObject.GetComponentInParent<Room>();
camGoto = true;
if (!colList.Contains(other))
colList.Add(other);
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.GetComponentInParent<Room>())
{
if (colList.Contains(other))
colList.Remove(other);
}
}
Upon starting the game I get a bunch of "NullReferenceException: Object reference not set to an instance of an object PlayerController.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/PlayerController.cs:63)" (presumably because those objects didn't get their parent set yet?). When I collide with something else (in my case another player, only without the controller script) I get those errors again, also for the Exit this time.
Any explanation why this is happening/how to fix it? Everything seems to work despite the errors but it doesn't feel right just letting them be.
Answer by Bunny83 · May 03, 2017 at 08:52 AM
The only thing that could really cause a Null ref exception here is your "colList". Are you sure you created an instance of your List?
So does your declaration looks like this:
List<Collider2D> colList;
or like this:
List<Collider2D> colList = new List<Collider2D>();
The latter would be correct. In the first case you only declared a variable that can hold an instance of a generic list but initially contains null;
Obviously doing the latter private List colList; void Start () { colList = new List(); //more stuff here...}
You shouldn't use Start for things like that. If you insist on using a callback from Unity, use Awake. Look, Unity never would call "OnTriggerEnter2D" or "OnTriggerExit2D" without passing a valid "Collider2D" as parameter. So we can be sure that other is not null (unless you call those methods manually which you should never do). Every valid Collider2D component can access it's gameObject it's attached to. "GetComponentInParent" could return null if no component was found. However since you don't use the returned value anywhere, it can't cause a null-ref-exception. The only thing left in the code you have posted is your "colList" variable.
Even if the object is somehow destroyed at the moment it enters, the error would be different. If the code you have posted is your actual code, it can only be your "colList" variable that is null.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
NullReferenceException script problem? 0 Answers
[Solved] Actually totally explainable NRE with 2D array 0 Answers
Null Reference Exception: Object Reference, with base class? 1 Answer