Hi All,
I’ve been keeping my Lives and Scores in a script attached to the player object along with its sprites, colliders and controllers, because the player sprite is consistent between scenes this seems to work ok.
But as my game develops from the basics into the niceties of proper screens for game over and level transitions, and alternative player characters, I think i’m going to need a better management of all of this than have it bolted directly to the player. Soooo…
Where do you all think is the best place to keep the persistent script to track these things? In with the UI itself? An empty game object? My guess is that the player would continue to look after his collision, but knows nothing about scoring so would just pass the collided object name (or other value) to a scoring script that knows everything about scoring and nothing else.
Anyway, this is the script i’ve got so far, and in case it’s useful to anyone as new as myself, the key to persistence between Scenes is the static keyword and the DontDestroyOnLoad bit.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class Score : MonoBehaviour {
public Text scoreText;
public int objectValue=15;
public Text livesText;
public int maxLives;
public static int score;
public List<string> collectedObjects;
public static int lives;
void Awake() {
DontDestroyOnLoad(this);
}
// Use this for initialization
void Start () {
//score = 0;
Debug.Log ("Score:"+score);
UpdateScore ();
//lives = 30;
maxLives = 3;
Debug.Log ("Lives:"+lives);
UpdateLives ();
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Collectible")
{ Debug.Log ("Collecting");
collectedObjects.Add (collision.gameObject.name);
Destroy (collision.gameObject);
score += objectValue;
UpdateScore();
}
if (collision.gameObject.tag == "Enemy")
{ Debug.Log ("Oops");
Destroy (gameObject);
lives+=1;
UpdateLives ();
// TODO:
// if (lives >= maxLives) Application.LoadLevel('GameOver');
// else...
Application.LoadLevel(Application.loadedLevelName);
}
}
void UpdateScore(){
scoreText.text = "Score:\n" + score;
}
void UpdateLives(){
livesText.text = "Lives:\n" + (maxLives - lives);
}
}