Ok, so this might be a little long, but I’ll try to cut up the code to be as quick as i can. The quick and dirty is this: between debug.Log “start here”(2nd code block, line 24) and “Null here” (1st code block, line 27) my player object goes from being a player to being Null. I’m stumped.
On the “Start here” the debug line returns with “Start Here! Player (Player) is still good and of type ‘Player’ here.”
On debug logs “1” through “8” is returns this: “1” or “3” or “8” (depending on the line). whereas it should say “# Player (Player)”.
Which of course means that as soon as i try to do anything at all after the “8” debug, such as “ShowLifeCount(extraLives);”, I get a NullReferenceException.
Please help me find the gremlins.
Here are the relevant code snippets:
public class GameManager : MonoBehaviour
{
public static GameManager gameManager = null;
public Player player;
private void Awake()
{
if (gameManager == null)
{
gameManager = this;
}
else if (gameManager != this)
{
Destroy(gameObject);
}
DontDestroyOnLoad(gameObject);
}
private void Start()
{
player = GameObject.FindWithTag("Player").GetComponent<Player>();
}
public void LoseOneLife()
{
Debug.Log(player + " is Null here");
extraLives--;
ShowLifeCount(extraLives);
CheckIfGameOver();
}
}
public class Projectile : MonoBehaviour
{
private Player player;
private GameManager gameManager;
private void Start()
{
gameManager = FindObjectOfType<GameManager>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
CollideWithPlayer(collision);
}
private void CollideWithPlayer(Collider2D other)
{
if (other.gameObject.CompareTag("Player"))
{
player = other.gameObject.GetComponent<Player>();
if (player != null)
{
Debug.Log("Start Here! " + gameManager.player + " is still good and of type 'Player' here.");
player.TakeDamage(projectileDamage);
}
else
{
Debug.Log("player is null");
}
Destroy(gameObject);
}
}
}
public class Player : MonoBehaviour
{
private GameManager gameManager;
private void Start()
{
gameManager = FindObjectOfType<GameManager>();
}
public void TakeDamage(int damageTaken)
{
Debug.Log("1 " + gameManager.player);
if (vulnerable)
{
Debug.Log("2 " + gameManager.player);
myHealth -= damageTaken;
Debug.Log("3 " + gameManager.player);
CheckDeath();
}
}
private void CheckDeath()
{
Debug.Log("4 " + gameManager.player);
if (myHealth <= 0)
{
Debug.Log("5 " + gameManager.player);
AudioSource.PlayClipAtPoint(deathSound, transform.position, 1f);
Debug.Log("6 " + gameManager.player);
gameObject.SetActive(false);
Debug.Log("7 " + gameManager.player);
gameManager.LoseOneLife();
}
}
}