Singleton HELP
I need to implement these codes in singleton but I have no idea about how to do it. I am new at coding Anyone can help? Or show to the way how to do it ?
Thanks!
using GooglePlayGames; using GooglePlayGames.BasicApi; using UnityEngine;
public class GooglePlayGameScript : MonoBehaviour {
// Use this for initialization
void Start () {
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().Build();
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.Activate();
SignIn();
}
void SignIn()
{
Social.localUser.Authenticate(success => { });
}
#region Leaderboards
public static void AddScoreToLeaderboard(string leaderboardId, long score)
{
Social.ReportScore(score, leaderboardId, success => { });
}
public static void ShowLeaderboardsUI()
{
Social.ShowLeaderboardUI();
}
#endregion /Leaderboards
using UnityEngine;
public class ManagerScript : MonoBehaviour {
public static ManagerScript Instance { get; private set; }
public static int Counter { get; private set; }
// Use this for initialization
void Start () {
Instance = this;
}
public void IncrementCounter()
{
Counter++;
UIScript.Instance.UpdatePointsText();
}
public void RestartGame()
{
GooglePlayGameScript.AddScoreToLeaderboard(GPGSIds.leaderboard_leaderboard, Counter);
Counter = 0;
UIScript.Instance.UpdatePointsText();
}
}
using UnityEngine;
using UnityEngine.UI;
public class UIScript : MonoBehaviour {
public static UIScript Instance { get; private set; }
// Use this for initialization
void Start () {
Instance = this;
}
[SerializeField]
private Text pointsTxt;
public void ShowLeaderboards()
{
GooglePlayGameScript.ShowLeaderboardsUI();
}
public void UpdatePointsText()
{
pointsTxt.text = ManagerScript.Counter.ToString();
}
}
Answer by Jawchewa · Apr 28, 2017 at 05:33 AM
In my experience, the easiest way to create the functionality of a singleton in Unity is to have a public static instance of your script, and use the script's OnAwake function to set the variable to be equal to the first instance that is created. Something like this:
public class MyClass : MonoBehaviour {
public static MyClass instance = null;
void Awake()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(gameObject);
}
}
}
This will limit you to only having one instance of your script at any time.
Your answer
Follow this Question
Related Questions
How can I handle scripts correctly? What's a good way to apply scripts to GameObjects? 1 Answer
script help 1 Answer
pick up object problem 0 Answers
can i get help please 0 Answers
I create material with script but it does not render right 0 Answers