- Home /
Question by
Bigfoob · Aug 14, 2015 at 08:30 PM ·
scripting problemunity 4.6singleton
Code not properly setting value to singleton C# Unity 4.6
I'm making a remake of 1981 Donkey Kong and I'm trying to increase the value of score when a barrel is destroyed or jumped over but for some reason my values are not being set properly when I check the values my score doesn't change and the livesleft goes from 3 to 2 just fine but once the scene reloads it stays at 2.
I just now thought it may have something to do with the code reloading the scene on death as the game manager script is on an empty gameobject that is a parent to the player character.
Here is the singleton script
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameManager : MonoBehaviour {
public Text livesleft;
private static GameManager instance;
public int lives;
public bool isdead;
public bool haslostlife = false;
public Text curScore;
public int timesdied;
public int highscore;
public Text curhighscore;
public static GameManager Instance{
get
{
if(instance == null){
GameObject go = new GameObject ("GameManager");
go.AddComponent<GameManager>();
}
return instance;
}
}
public int score;
void Awake()
{
instance = this;
DontDestroyOnLoad(this.gameObject);
}
void OnEnable(){lives = 3;}
void FixedUpdate()
{
//Debug.Log("Lives left" + lives);
//Debug.Log("Times Died" + timesdied);
Debug.Log("score = " + score);
Debug.Log("high score = " + highscore);
CheckLives();
curScore.text = "" + score;
if (score > highscore )
{
score = highscore;
curhighscore.text = "" + highscore;
}
/* if (timesdied == 2 && lives == 2)
{
lives = 1;
}
if (timesdied == 3){
}*/
}
void CheckLives()
{
livesleft.text = "" + lives;
}
}
This script is on the Barrels, here is the relevant code.
if (other.gameObject.tag == "Player"){
player = other.gameObject;
GameManager.Instance.timesdied = GameManager.Instance.timesdied + 1;
GameManager.Instance.lives = GameManager.Instance.lives + -1;
StartCoroutine(Restart ());
}
if (other.gameObject.tag == "HammerMode")
{
GameManager.Instance.score = GameManager.Instance.score + 500;
Destroy(this.gameObject);
}
}
IEnumerator Restart()
{
yield return new WaitForSeconds(3);
Destroy(player);
Application.LoadLevel("main");
}
And from my Player Script (it uses a trigger below his feet to collide with the barrel for scoring):
// In OnTriggerExit2D (collider other)
if (other.gameObject.tag == "Barrel")
{
GameManager.Instance.score = GameManager.Instance.score + 100;
Debug.Log ("Hey");
Debug.Log(GameManager.Instance.score);
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220611235915im_/https://answers.unity.com/themes/thub/images/avi.jpg)