- Home /
2D Game Checkpoint & Respawning
NullReferenceException: Object reference not set to an instance of an object LevelManager.RespawnPlayer () (at Assets/Scripts/LevelManager.cs:26) KillPlayer.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/KillPlayer.cs:25)
heres KillPlayer Script: using UnityEngine; using System.Collections;
public class KillPlayer : MonoBehaviour {
public LevelManager levelManager;
// Use this for initialization
void Start()
{
levelManager = FindObjectOfType<LevelManager>();
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.name == "Player")
{
levelManager.RespawnPlayer();
}
}
} heres LevelManger script: using UnityEngine; using System.Collections;
public class LevelManager : MonoBehaviour {
public GameObject currentCheckpoint;
private CharacterController player;
// Use this for initialization
void Start()
{
player = FindObjectOfType<CharacterController>();
}
// Update is called once per frame
void Update()
{
}
public void RespawnPlayer()
{
Debug.Log("Player Respawn");
player.transform.position = currentCheckpoint.transform.position;
}
}
heres Checkpoint Script: using UnityEngine; using System.Collections;
public class Checkpoint : MonoBehaviour { public LevelManager levelManager; // Use this for initialization void Start() { levelManager = FindObjectOfType(); }
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.name == "Player")
{
levelManager.currentCheckpoint = gameObject;
}
}
}
Answer by Statement · Dec 19, 2019 at 06:29 PM
The error happens here.
Either player is null or currentCheckpoint is null.
public void RespawnPlayer()
{
Debug.Log("Player Respawn");
player.transform.position = currentCheckpoint.transform.position;
}
Fix it by first checking which one of them are null and then figure out why they are null, and make sure they aren't null.
Try Debug.Log("Player " + player);
and Debug.Log("Checkpoint " + currentCheckpoint);
and read the console to further narrow the problem down.
Perhaps you haven't entered a checkpoint yet.
Answer by Snifferito1337 · Dec 19, 2019 at 06:38 PM
bro
public void RespawnPlayer() { Debug.Log("Player " + player); player.transform.position = currentCheckpoint.transform.position; } I ` I've did it in LevelManager but it's same thing.. Same Error.. :(
It means that currentCheckpoint is never set. In Checkpoint.cs, add a Debug.Log inside OnTriggerEnter2D so you can test that the checkpoint is set in Level$$anonymous$$anager.
Your answer
![](https://koobas.hobune.stream/wayback/20220612220411im_/https://answers.unity.com/themes/thub/images/avi.jpg)