- Home /
OnCollisionEnter GameObject throws NullReferenceException
I have two game objects with box colliders. One has a rigidbody. This is the player. The other object is a room. I am trying to test to see if the player is in the room. This behavior will be cloned across multiple rooms so its kind of a player tracking system.
When the player enters the rooms box collider, OnCollisionEnter fires. I pass the gameObject of the player to the roomController where I try and add the gameObject parameter (the player) to a List. The problem is that it throws a null reference exception. One of the things that I noticed when I stepped through my code is that the gameObject > base > gameObject > base trail seems to go on forever.
Another note: InteractableController (from which PlayerController inherits) is a class that inherits from MonoBehavior and only implements one virtual method called Interact() that is empty. So I don't think thats the problem.
public class PlayerController : InteractableController {
void OnCollisionEnter(Collision collisionInfo){
if (CollisionType.getCollisionType(collisionInfo.collider) == CollisionType._CollisionType.room_trigger){
collisionInfo.collider.gameObject.GetComponent<RoomController>().RoomEntered(gameObject);
}
LogCollision(collisionInfo);
}
void OnCollisionExit(Collision collisionInfo){
if (CollisionType.getCollisionType(collisionInfo.collider) == CollisionType._CollisionType.room_trigger){
collisionInfo.gameObject.GetComponent<RoomController>().RoomExited(transform.gameObject);
}
RemoveCollision (collisionInfo);
}
}
public class RoomController : MonoBehaviour {
List<GameObject> charactersInRoom;
void Active () {
charactersInRoom = new List<GameObject>();
}
public void RoomEntered(GameObject source){
charactersInRoom.Add (source);
}
public void RoomExited(GameObject source){
charactersInRoom.Remove (source);
}
}
And my stack trace
NullReferenceException: Object reference not set to an instance of an object
RoomController.RoomEntered (UnityEngine.GameObject source) (at Assets/Scripts/Gameplay/RoomController.cs:31)
RoomController.OnCollisionEnter (UnityEngine.Collision info) (at Assets/Scripts/Gameplay/RoomController.cs:40)