Hi All
I want to keep the score and No. of lives from one level to other but it’s not working properly. I tried Static void for lives variable but it did not work.
This is what I am doing
I have 2 Levels Level1 and level2
In level one I have an empty object “Life” and I have assigned a script (class) LifeManager to that object that has variables to store No of lives at the start and current.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class LifeManager : MonoBehaviour
{
public int startinglives;
public static int lifecounter;
public static int lifeLeft;
private Text theText;
public GameObject GameOverScreen; // For Gmae Over Screen
// Start is called before the first frame update
void Start()
{
theText = GetComponent<Text>();
lifecounter = startinglives;
}
// Update is called once per frame
void Update()
{
theText.text = "X " + lifecounter;
if (lifecounter < 0)
{
GameOverScreen.SetActive(true);
}
}
public void GiveLife()
{
lifecounter++;
}
public void TakeLife()
{
lifecounter--;
}
}
In level 2 I have a Script LifeManager2 that is attached to that empty object “Life” instead of LifeManager that is discussed above.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LifeManager2 : MonoBehaviour
{
public int lifeLeft2;// for new scene 2
private Text theText;
public GameObject GameOverScreen; // For Gmae Over Screen
// Start is called before the first frame update
void Start()
{
theText = GetComponent<Text>();
lifeLeft2 = LifeManager.lifecounter; // for new scene 2 3#
}
// Update is called once per frame
void Update()
{
{
theText.text = "X " + lifeLeft2;
if (lifeLeft2 < 0)
{
GameOverScreen.SetActive(true);
}
}
}
}
Now No. of lives are working fine from one scene(level) to others but when I call Life.TakeLife(); method I get following error.
“NullReferenceException: Object reference not set to an instance of an object”
I call the method from a script PlayerCollision.cs that is attached to the player in both scenes.
Can you anyone help me to figure out what is wrong here and is there any way to simplify this script instead of creating a separate lifeManager script for each scene can I create one variable for all the scenes.
Thanks in advance