C# issues ; OnTriggerEnter2D

Hello All!

I’m having issues with my 2D game code, more specifically with OnTriggerEnter2D.

I get this error:

NullReferenceException: Object reference not set to an instance of an object
KillPlayer.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/KillPlayer.cs:21)

Here is my code.

LevelManager.cs:

using UnityEngine;
using System.Collections;

public class LevelManager : MonoBehaviour {

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	
	public void RespawnPlayer () {
		Debug.Log("Player Respawned.");
	}
}

KillPlayer.cs:

using UnityEngine;
using System.Collections;

public class KillPlayer : MonoBehaviour {

	public LevelManager levelManager;

	// Use this for initialization
	void Start () {
		levelManager = GetComponent<LevelManager>();
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	
	void OnTriggerEnter2D (Collider2D other) {
		
		if(other.name == "Player") {
			levelManager.RespawnPlayer();
		}
		
	}
}

I have no idea what to do. Any help?

Thanks in advance!

A debugger would be the quickest way to figure out what’s null, but since the error gives you the exact line number and there’s only a single method call on that line, I’m going to take a wild guess that your “levelManager” variable is null.