In the game we'll need an object that is persisted throughout the gameplay session so that we can keep track of score, lives, health, etc.
Below is a simple class definition for GameData, we'll add more to this as we progress.
This script will be attached to the GameManager in the first game Scene and will be persisted throughout the game since it uses the singleton design pattern.
Add GameData script to an Empty GameObject: named: GameManager in your starting scene, so it will be executed as a singleton and shows up as 'DontDestroyOnLoad' in the Hierarchy when the game is played.
DontDestroyOnLoad - in Play-mode
How to use GameData Singleton To use the singleton reference in another class use the following syntax, for example, when calling the Add method from the PlayerController script:
Example of using GameData singleton in PlayerController.cs
GameData.instanceRef.Add( item.value );
GameData Class Definition
modified 4/10/2020
using System.Collections;using System.Collections.Generic;using UnityEngine;/// <summary>/// Singleton Object to store all GameData/// Is not destroyed when changing scenes/// </summary>publicclassGameData : MonoBehaviour{publicstaticGameData instanceRef; //null //variable that can point to a GameData objectprivateint score;privateint health;privateint levelScore; //project 3/// <summary>/// Properties - provide read/write access to variables/// </summary>publicintScore { get { return score; } //Read access// set { totalScore = value; } //write access }publicintHealth { get { return health; } //read-only acccess }// Awake is called before Start() is called on any GameObject// Other objects have dependencies on this object so it must be created firstvoidAwake() {if( instanceRef ==null) //this code hasn't been executed before { instanceRef =this; //point to object instance currently executing this codeDontDestroyOnLoad(this.gameObject); //don't destroy the gameObject this is attached to }else//this object is not the first, it's an imposter that must be destroyed {DestroyImmediate(this.gameObject);Debug.Log("Destroy GameData Imposter"); }//initialize after destroying imposters score =0; health =100; levelScore =0; } //end Awake//will be executed in PlayerController when colliding with a collectiblepublicvoidAdd( int value) { totalScore += value;Debug.Log("Score updated: "+ score); //display score in console }publicvoidTakeDamage( int value) { health -= value;Debug.Log("health updated: "+ health); //display health in consoleif( health <=0) {Debug.Log("Health less than 0"); //display health in console } }//called when restarting the miniGamepublicvoidResetGameData() { score =0; health =100; }}//end class GameData
Resets Score and Health to correct initial values. Public, so it can be executed from MiniGameManager Script.