I would like to set up a script that keeps track of the player’s health, wealth and current arms from scene to scene, as well as certain, scene specific information such as enemies killed that I otherwise know only how to relay between scripts/objects via SendMessage.
After looking around the Internet and Unity fora, I found recommendations of the use of a singleton script for problems that look similar to mine. I’ve run into two problems: 1.) Most of the example scripts are in C#, and I’m using UnityScript. 2.) I’m getting a recurring error message (“An instance of type ‘GameManagerClass’ is required to access non static member ‘IncreasePlayersMoney’.” where IncreasePlayersMoney is the singleton’s variable keeping track of how much money the player has accumulated.)
Here are the scripts (the first is the singleton; the second is the gameObject which is to report to the singleton by how much the player’s total wealth is to be increased).
Singleton:
class GameManagerClass
{
private static var Instance : GameManagerClass = new GameManagerClass();
static var PlayersGeld : int;
public static function GetInstance() : GameManagerClass
{
if(Instance == null)
Instance = new GameManagerClass();
return Instance;
}
private function IncreasePlayersGeld (amount : int)
{
PlayersGeld += amount;
Debug.Log("Geldsumme des Spielers :" + PlayersGeld);
}
private function GameManagerClass()
{
}
}
GameObject reporting to the singleton:
#pragma strict
function Start () {
}
function Update () {
}
function OnCollisionEnter(other : Collision)
{
if(other.gameObject.tag == "Player")
{
var gameManagerRef : GameManagerClass = GameManagerClass.GetInstance();
GameManagerClass.IncreasePlayersGeld(5);
}
}