[2D] Plateformer : Unable to Respawn

Updated on December 15, 2017 in [A] 2D
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
4 on August 20, 2016

Hello Dear Fellow Staff Member , I have receive this problem that I can`t Respawn when i died so what should i do

References:
Error

NullReferenceException: Object reference not set to an instance of an object
GameMaster.KillPlayer (.Player player) (at Assets/GameMaster.cs:28)
Player.DamagePlayer (Int32 damage) (at Assets/Player.cs:23)
Player.Update () (at Assets/Player.cs:17)

GameMaster Scripts

using UnityEngine;
using System.Collections;

public class GameMaster : MonoBehaviour {

public static GameMaster gm;

void Start () {
if (gm == null) {
gm = GameObject.FindGameObjectWithTag (“GM”).GetComponent<GameMaster>();
}
}

public Transform playerPrefab;
public Transform spawnPoint;
public int spawnDelay = 2;

public IEnumerator RespawnPlayer () {
Debug.Log (“TODO: Add waiting for spawn sound”);
yield return new WaitForSeconds (spawnDelay);

Instantiate (playerPrefab, spawnPoint.position, spawnPoint.rotation);
Debug.Log (“TODO: Add Spawn Particles”);
}

public static void KillPlayer (Player player) {
Destroy (player.gameObject);
gm.StartCoroutine(gm.RespawnPlayer());
}

}

Players Scripts

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {

[System.Serializable]
public class PlayerStats {
public int Health = 100;
}

public PlayerStats playerStats = new PlayerStats();

public int fallBoundary = -20;

void Update () {
if (transform.position.y <= fallBoundary)
DamagePlayer (9999999);
}

public void DamagePlayer (int damage) {
playerStats.Health -= damage;
if (playerStats.Health <= 0) {
GameMaster.KillPlayer(this);
}
}

}

So I hope that You Staff Members may be able to help me to go thought this Error
Thanks

  • Liked by
Reply
1 on August 20, 2016

May I ask why you have the gm variable in your GameMaster script when it just refers to the script it is in without accessing it from other scripts?

on August 20, 2016

Hmm. I just copy the script from Brackeys youtube ep 12

Show more replies
  • Liked by
Reply
Cancel
0 on August 24, 2016

Inside the update method just below the damagePlayer you need to type:
StartCoroutine(RespawnPlayer());

RespawnPlayer is an iEnumerator, which means it is a coroutine and you need to call it using StartCoroutine.

  • Liked by
Reply
Cancel
0 on December 15, 2017

I had the same error and found the solution for me on the comments of the 12 episode:

here’s the fix for it , look for this line.

void Start() {

if(gm==null){

gm = this; //GameObject.FindGameObjectWithTag(“GM”).GetComponent<GameMaster>();

}

}

mask out the GameObject with // in front ( or just delete it ) and replace it with this;

it’s been awhile , you probably found this already but i put it here in case of some has the same problem.

  • Liked by
Reply
Cancel