Question by
Raviraja190 · Jul 22, 2017 at 10:45 AM ·
gameobjectdestroydontdestroyonloaddestroy object
Dont destroy on load is destroying my Game Manager
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour {
public static GameManager Instance
{
get
{
if(_instance !=null)
{
return _instance;
}
else
{
GameObject gameManager = new GameObject("GameManager");
_instance = gameManager.AddComponent <GameManager>();
return _instance;
}
}
}
private static GameManager _instance;
public string titlescreenname = "TitleScene";
[HideInInspector]
public int PreviousScore = 0;
public float pointsperunittravelled = 0.0f;
private static float highScore = 0.0f;
private bool hasSaved = false;
private float Score = 0.0f;
public float gamespeed = 10.0f;
private bool gameOver =false;
// Use this for initialization
void Start ()
{
if (_instance != this)
{
if (_instance == null)
{
_instance = this;
}
else
{
Destroy (gameObject);
}
}
LoadHighScore ();
DontDestroyOnLoad(gameObject);
}
// Update is called once per frame
void Update () {
if (SceneManager.GetActiveScene().name != titlescreenname) {
if (GameObject.FindGameObjectWithTag ("Player") == null) {
gameOver = true;
}
if (gameOver) {
if (!hasSaved)
{
SaveHighScore ();
PreviousScore = (int)Score;
hasSaved = true;
}
if (Input.anyKeyDown) {
SceneManager.LoadScene(titlescreenname);
}
}
if (!gameOver) {
Score += pointsperunittravelled * gamespeed * Time.deltaTime;
if (Score > highScore) {
highScore = Score;
}
}
}
else {
//Reset stuff for next game
ResetGame();
}
}
void ResetGame()
{
Score = 0.0f;
gameOver = false;
hasSaved = false;
}
void LoadHighScore()
{
highScore = PlayerPrefs.GetInt ("HighScore");
}
void SaveHighScore()
{
PlayerPrefs.SetInt ("HighScore", (int)highScore);
PlayerPrefs.Save ();
}
void OnGUI()
{
if(SceneManager.GetActiveScene().name != titlescreenname)
{
int currentscore = (int)Score;
int currenthighScore = (int)highScore;
GUILayout.Label ("Score: " + currentscore.ToString ());
GUILayout.Label ("HighScore: " + currenthighScore.ToString ());
if(gameOver==true)
{
GUILayout.Label("GameOver! PreesanyKey to reset!");
}
}
}
}
Comment