- Home /
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!
Answer by NewPath · Oct 16, 2015 at 08:57 PM
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.
How would I go about fixing that? I'm assigning level$$anonymous$$anager to the component in Start()
First, if your intent is to grab it at runtime like that, I would make it private for encapsulation purposes.
I would assume that the GetComponent() call did not find it, and thus returned null. Again, a fairly simple question that you can answer in seconds by simply debugging.
Are you sure that script is actually attached to the object in question and not one of its children?
The $$anonymous$$illPlayer script is attatched to a game objet called spikes (set to be a trigger) and the Level$$anonymous$$anager script is attached to an empty game object. Also, what shall I do if level$$anonymous$$anager returns null?
So think about what you are doing. You're calling GetComponent() from an object that you already know does not have a Level$$anonymous$$anager associated with it. Why would that return anything but null.
1) Leave level$$anonymous$$anager public as you have it. 2) Remove the GetComponent() call altogether. 3) In the editor, drag the empty game object onto the level$$anonymous$$anager property on your spikes object. You should see it create a reference to the Level$$anonymous$$anager script.
Thank you, I'll try it. I'll mark the answer as accepted once it is tested.
Your answer