Skip to content

Instantly share code, notes, and snippets.

@ZeredaGames
Last active March 8, 2019 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZeredaGames/2f759bc0dda64c7f0663d4470e1dc122 to your computer and use it in GitHub Desktop.
Save ZeredaGames/2f759bc0dda64c7f0663d4470e1dc122 to your computer and use it in GitHub Desktop.
How i have it set up thus far.
#region Leaderboards
// May need to set string's public and drag this scripts onto a temp GO to make
// ease of retreiving the corrects spelling for tags (There are a lot)
// so you could make them private again. (This is if your tags are not set up)
//[Header("Leaderboards Settings:")]
private string OpenLeaderboardButtonTag = "OpenLeaderboardButton";
private string CloseLeaderboardButtonTag = "CloseLeaderboardButton";
private string LeaderboardTag = "Leaderboard";
private string ListingContainerTag = "LeaderboadContainer";
private string NameOfListingPrefab = "LeaderboardListingPrefab";
private Button OpenLeaderboardButton;
private Button CloseLeaderboardButton;
private GameObject LeaderboardPanel;
/// <summary>
/// The prefab we created to create a new listing.
/// </summary>
private GameObject listingPrefab;
/// <summary>
/// The container we display all the new listings in.
/// </summary>
private Transform listingContainer;
private void GetLeaderboarder(string leaderboard)
{
OpenLeaderboardButton = GameObject.FindGameObjectWithTag(OpenLeaderboardButtonTag).GetComponent<Button>();
CloseLeaderboardButton = GameObject.FindGameObjectWithTag(CloseLeaderboardButtonTag).GetComponent<Button>();
var requestLeaderboard = new GetLeaderboardRequest { StartPosition = 0, StatisticName = leaderboard, MaxResultsCount = 20 };
PlayFabClientAPI.GetLeaderboard(requestLeaderboard, OnGetLeadboard, OnErrorLeaderboard);
}
private void OnGetLeadboard(GetLeaderboardResult result)
{
if (CheckIfLeaderboadPanelExists(true))
{
foreach (PlayerLeaderboardEntry player in result.Leaderboard)
{
listingContainer = GameObject.FindGameObjectWithTag(ListingContainerTag).gameObject.transform;
listingPrefab = (GameObject)Resources.Load(Application.dataPath + "Prefabs/" + NameOfListingPrefab);
GameObject tempListing = Instantiate(listingPrefab, listingContainer);
LearderboardListing LL = tempListing.GetComponent<LearderboardListing>();
LL.playerNameText.text = player.DisplayName;
LL.playerScoreText.text = player.StatValue.ToString();
LL.playerRank.text = player.Position.ToString();
if (Instance.DebugMode)
Debug.Log(player.Position + ": " + player.DisplayName + ": " + player.StatValue);
}
}
}
private void CloseLeaderboardPanel()
{
if (CheckIfLeaderboadPanelExists(false))
{
for (int i = listingContainer.childCount - 1; i >= 0; i--)
{
Destroy(listingContainer.GetChild(i).gameObject);
}
}
}
private void OnErrorLeaderboard(PlayFabError error)
{
if (CheckIfLeaderboadPanelExists(false))
{
if (Instance.DebugMode)
Debug.LogError(error.GenerateErrorReport());
}
else {
if (Instance.DebugMode)
{
Debug.Log("Leaderboard not present in scene.");
Debug.LogError(error.GenerateErrorReport());
}
}
}
private bool CheckIfLeaderboadPanelExists(bool enable)
{
LeaderboardPanel.SetActive(enable);
if (!Equals(DevSettingsPanel, null))
{
return false;
}
else {
return true;
}
}
#endregion
#region Extras
#region Encryption
/**
* @file ZPlayerPrefs.cs
* @brief ZPlayerPrefs.cs
* @create 3/17/2015 3:26:21 PM
* @author ZETO
* @Copyright (c) 2015 Studio ZERO. All rights reserved.
*/
/*==============================================================================
EDIT HISTORY FOR MODULE
when who what, where, why
(3/3/2019) ZG Added to my script, not taking credit for anything in region.
---------- --- ------------------------------------------------------------
ZETO Initial Create
==============================================================================*/
// Set false if you don't want to use encrypt/decrypt value
// You could use #if UNITY_EDITOR for check your value
public static bool useSecure = true;
// You should Change following password and IV value using Initialize
static string strUser = "NewUser";
static string strPassword = "IamZG!123";
static string strSalt = "dD123a12Fg";
static bool hasSetPassword = false;
private static void CheckPasswordSet()
{
if (!hasSetPassword)
{
Debug.LogWarning("Set Your Own Password & Salt!!!");
}
}
public static void InitializeNewEncryptionKey(string newUser, string newPassword, string newSalt)
{
strPassword = newPassword;
strSalt = newSalt;
strUser = newUser;
hasSetPassword = true;
}
public static void DeleteAll()
{
Instance.ClearPlayerPrefs = true;
PlayerPrefs.DeleteAll();
}
public static void DeleteKey(string key)
{
PlayerPrefs.DeleteKey(key);
}
public static void Save()
{
CheckPasswordSet();
PlayerPrefs.Save();
}
public static void SetString(string key, string value)
{
PlayerPrefs.SetString(Encrypt(key, strPassword), Encrypt(value, strPassword));
}
public static void SetStringPlus(string constant, string constAttachedValue, string valueToSave)
{
CheckPasswordSet();
SetString(constant + constAttachedValue, valueToSave);
}
public static void SetStringPlus(string constant, int constAttachedValue, string valueToSave)
{
CheckPasswordSet();
SetString(constant + constAttachedValue, valueToSave);
}
public static void SetStringPlus(string constant, float constAttachedValue, string valueToSave)
{
CheckPasswordSet();
SetString(constant + constAttachedValue, valueToSave);
}
public static void SetInt(string key, int value)
{
string strValue = System.Convert.ToString(value);
SetString(key, strValue);
}
public static void SetIntPlus(string constant, int constAttachedValue, int valueToSave)
{
CheckPasswordSet();
SetInt(constant + constAttachedValue, valueToSave);
}
public static void SetIntPlus(string constant, string constAttachedValue, int valueToSave)
{
CheckPasswordSet();
SetInt(constant + constAttachedValue, valueToSave);
}
public static void SetIntPlus(string constant, float constAttachedValue, int valueToSave)
{
CheckPasswordSet();
SetInt(constant + constAttachedValue, valueToSave);
}
public static void SetFloat(string key, float value)
{
string strValue = System.Convert.ToString(value);
SetString(key, strValue);
}
public static void SetFloatPlus(string constant, string constAttachedValue, float valueToSave)
{
CheckPasswordSet();
SetFloat(constant + constAttachedValue, valueToSave);
}
public static void SetFloatPlus(string constant, float constAttachedValue, float valueToSave)
{
CheckPasswordSet();
SetFloat(constant + constAttachedValue, valueToSave);
}
public static void SetFloatPlus(string constant, int constAttachedValue, float valueToSave)
{
CheckPasswordSet();
SetFloat(constant + constAttachedValue, valueToSave);
}
public static int GetInt(string key)
{
CheckPasswordSet();
return GetInt(key, 0);
}
public static int GetInt(string key, int defaultValue, bool isDecrypt = true)
{
int retValue = defaultValue;
string strValue = GetString(key);
if (int.TryParse(strValue, out retValue))
{
return retValue;
}
else {
return defaultValue;
}
}
public static int GetIntPlus(string constant, int constAttachedValue)
{
CheckPasswordSet();
return GetInt(constant + constAttachedValue, 0);
}
public static float GetFloat(string key)
{
CheckPasswordSet();
return GetFloat(key, 0.0f);
}
public static float GetFloat(string key, float defaultValue, bool isDecrypt = true)
{
float retValue = defaultValue;
string strValue = GetString(key);
if (float.TryParse(strValue, out retValue))
{
return retValue;
}
else {
return defaultValue;
}
}
public static float GetFloatPlus(string constant, float constAttachedValue)
{
CheckPasswordSet();
return GetFloat(constant + constAttachedValue, 0.0f);
}
public static string GetString(string key)
{
string strEncryptValue = GetRowString(key);
return Decrypt(strEncryptValue, strPassword);
}
public static string GetString(string key, string defaultValue)
{
string strEncryptValue = GetRowString(key, defaultValue);
return Decrypt(strEncryptValue, strPassword);
}
public static string GetStringPlus(string constant, string constAttachedValue)
{
CheckPasswordSet();
return GetString(constant + constAttachedValue, "");
}
public static string GetRowString(string key)
{
CheckPasswordSet();
string strEncryptKey = Encrypt(key, strPassword);
string strEncryptValue = PlayerPrefs.GetString(strEncryptKey);
return strEncryptValue;
}
public static string GetRowString(string key, string defaultValue)
{
CheckPasswordSet();
string strEncryptKey = Encrypt(key, strPassword);
string strEncryptDefaultValue = Encrypt(defaultValue, strPassword);
string strEncryptValue = PlayerPrefs.GetString(strEncryptKey, strEncryptDefaultValue);
return strEncryptValue;
}
public static string Encrypt(string strPlain, string password)
{
if (!useSecure)
return strPlain;
try
{
if (!Equals(strPassword, password))
{
useSecure = false;
return strPlain;
}
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] iv = Encoding.UTF8.GetBytes("(Z;G;cW)(sA(Salt):" + strSalt + ")");
Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes("(Z;G;cW)(pA(Pass):" + strPassword + ")", iv, 555);
byte[] key = rfc2898DeriveBytes.GetBytes(15);
using (var memoryStream = new MemoryStream())
using (var cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(key, Encoding.UTF8.GetBytes(strSalt)), CryptoStreamMode.Write))
{
memoryStream.Write(Encoding.UTF8.GetBytes(strSalt), 0, Encoding.UTF8.GetBytes(strSalt).Length);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(strPlain);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
return Convert.ToBase64String(memoryStream.ToArray());
}
}
catch (Exception e)
{
Debug.LogWarning("Encrypt Exception: " + e);
return strPlain;
}
}
public static string Decrypt(string strEncript, string password)
{
if (!useSecure)
return strEncript;
try
{
if (!Equals(strPassword, password))
{
useSecure = false;
return strEncript;
}
byte[] cipherBytes = Convert.FromBase64String(strEncript);
using (var memoryStream = new MemoryStream(cipherBytes))
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] iv = Encoding.UTF8.GetBytes("(Z;G;cW)(sA(Salt):" + strSalt + ")");
memoryStream.Read(iv, 0, iv.Length);
// use derive bytes to generate key from password and IV
var rfc2898DeriveBytes = new Rfc2898DeriveBytes("(Z;G;cW)(pA(Pass):" + strPassword + ")", iv, 555);
byte[] key = rfc2898DeriveBytes.GetBytes(15);
using (var cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(key, iv), CryptoStreamMode.Read))
using (var streamReader = new StreamReader(cryptoStream))
{
string strPlain = streamReader.ReadToEnd();
return strPlain;
}
}
}
catch (Exception e)
{
Debug.LogWarning("Decrypt Exception: " + e);
return strEncript;
}
}
public static bool HasKey(string key)
{
CheckPasswordSet();
return PlayerPrefs.HasKey(Encrypt(key, strPassword));
}
#endregion
#region Clear Unity Purchasing Path (extra feature)
[MenuItem("Editors/ZeredaGamesEngine/Game Making Tools/Delete/Clear Unity Purchasing Path", false, 1)]
public static void OnClearUnityPurchasingPath()
{
if (EditorUtility.DisplayDialog("Clear Unity Purchasing Entries", "Are you sure you want to clear Unity Purchasing data for this project? ", "Clear", "Skip"))
{
string unityPurchasingPath = System.IO.Path.Combine(System.IO.Path.Combine(Application.persistentDataPath, "Unity"), "UnityPurchasing");
if (System.IO.Directory.Exists(unityPurchasingPath))
{
System.IO.Directory.Delete(unityPurchasingPath, true);
}
if (Instance.DebugMode)
{
string message = System.DateTime.Now.ToString();
Debug.Log("[" + message + "] [UNITY PURCHASING PATH CLEARED]");
}
}
}
#endregion
#region Extra Stuff (Not Currently Using)
public static long ElapsedTimeForAndroid()
{
if (Application.platform != RuntimePlatform.Android)
return 0;
AndroidJavaClass systemClock = new AndroidJavaClass("android.os.SystemClock");
return systemClock.CallStatic<long>("elapsedRealtime");
}
#endregion
#endregion
#region Facebook
void OnFacebookAwake()
{
#if FACEBOOK
FB.Init(OnFBInitComplete, OnFBHideUnity);
#endif
}
/// <summary>
/// Login with a facebook account. This kicks off the request to facebook
/// </summary>
private void OnLoginWithFacebookClicked()
{
ProgressBar.UpdateLabel("Logging In to Facebook..");
#if FACEBOOK
FB.LogInWithReadPermissions(new List<string>() { "public_profile", "email", "user_friends" }, OnHandleFBResult);
#endif
}
#if FACEBOOK
private void OnHandleFBResult(ILoginResult result)
{
if (result.Cancelled)
{
ProgressBar.UpdateLabel("Facebook Login Cancelled.");
ProgressBar.UpdateProgress(0);
}
else if(result.Error != null) {
ProgressBar.UpdateLabel(result.Error);
ProgressBar.UpdateProgress(0);
}
else
{
ProgressBar.AnimateProgress(0, 1, () => {
//second loop
ProgressBar.UpdateProgress(0f);
ProgressBar.AnimateProgress(0, 1, () => {
ProgressBar.UpdateLabel(string.Empty);
ProgressBar.UpdateProgress(0f);
});
});
_AuthService.AuthTicket = result.AccessToken.TokenString;
_AuthService.Authenticate(Authtypes.Facebook);
}
}
private void OnFBInitComplete()
{
if(AccessToken.CurrentAccessToken != null)
{
_AuthService.AuthTicket = AccessToken.CurrentAccessToken.TokenString;
_AuthService.Authenticate(Authtypes.Facebook);
}
}
private void OnFBHideUnity(bool isUnityShown)
{
//do nothing.
}
#endif
#endregion
#region Global DebugMode
/// <summary>
/// If true debug logs display in console, else they do not.
/// </summary>
[Tooltip("If true debug logs display in console, else they do not.")]
public bool DebugMode = true;
/// <summary>
/// Used to grab the current value of Debug Mode.
/// </summary>
public const string DEBUGMODEKEY = "DebugMode";
/// <summary>
/// Gets the debug mode from player preffs: Also check to see if Player preffs has been tampered with and corrects the issue.
/// </summary>
public static bool GetDebugMode
{
get
{
string message = PlayFabController.GetString(DEBUGMODEKEY);
bool checkString1 = Equals(message, "true");
bool checkString2 = Equals(message, "false");
bool checkString3 = Equals(message, "");
if (!checkString1 || !checkString2 || !checkString3)
{
Instance.DebugMode = false;
PlayFabController.SetString(DEBUGMODEKEY, Instance.DebugMode.ToString());
return Instance.DebugMode;
}
if (!checkString1 || !checkString2 || checkString3)
{
Instance.DebugMode = false;
PlayFabController.SetString(DEBUGMODEKEY, Instance.DebugMode.ToString());
return Instance.DebugMode;
}
if (!checkString1 || checkString2 || !checkString3)
{
Instance.DebugMode = false;
PlayFabController.SetString(DEBUGMODEKEY, Instance.DebugMode.ToString());
return Instance.DebugMode;
}
if (checkString1 || !checkString2 || !checkString3)
{
Instance.DebugMode = true;
PlayFabController.SetString(DEBUGMODEKEY, Instance.DebugMode.ToString());
return Instance.DebugMode;
}
return Instance.DebugMode;
}
}
/// <summary>
/// Sets a value indicating whether this <see cref="PlayFabController"/> on debug mode.
/// </summary>
/// <value><c>true</c> if on set debug mode; otherwise, <c>false</c>.</value>
public static bool OnSetDebugMode
{
set
{
PlayFabController.SetString(DEBUGMODEKEY, Instance.DebugMode.ToString());
Instance.DebugMode = value;
}
}
#endregion
#region Google Play
void OnGooglePlayAwake()
{
#if GOOGLEGAMES
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
.AddOauthScope("profile")
.RequestServerAuthCode(false)
.Build();
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.DebugLogEnabled = true;
PlayGamesPlatform.Activate();
#endif
}
/// <summary>
/// Login with a google account. This kicks off the request to google play games.
/// </summary>
private void OnLoginWithGoogleClicked()
{
#if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS))
Social.localUser.Authenticate((success) =>
{
if (success)
{
var serverAuthCode = PlayGamesPlatform.Instance.GetServerAuthCode();
_AuthService.AuthTicket = serverAuthCode;
_AuthService.Authenticate(Authtypes.Google);
}
});
#endif
}
#if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS))
void OnGooglePlay()
{
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
.AddOauthScope("profile")
.RequestServerAuthCode(false)
.Build();
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.DebugLogEnabled = true;
PlayGamesPlatform.Activate();
if (SignInButton != null)
{
SignInButton.onClick.AddListener(OnSignInButtonClicked);
}
else
{
Debug.Log("Please link your button in the inspector.");
}
if (HasKey("EMAIL"))
{
if (Instance.DebugMode)
Debug.Log("Google-Play:");
var request = new LoginWithGoogleAccountRequest { PlayerSecret = userEmail, CreateAccount = true };
PlayFabClientAPI.LoginWithGoogleAccount(request, OnLoginSuccess, OnPlayFabError);
}
else {
OnDisplayWarningWindow("[WARNING] No 'Email-Key' on this Server.");
}
}
#endif
#endregion
#region Internal Singleton
[Header("Internal Singleton:"), Tooltip("If True: this becomes a singleton.")]
public bool SetDontDestroyOnLoad = true;
private static string ScriptPrefabName = "PlayFabControllerPrefab";
/// <summary>
/// The instance of this script.
/// </summary>
public static PlayFabControllerPrefab Instance;
/// <summary>
/// In Case you wanted to call StartCoroutine in a static method
/// </summary>
public static MonoBehaviour monoBehaviour;
/// <summary>
/// Gets the get instance.
/// </summary>
/// <value>The get instance.</value>
public static PlayFabControllerPrefab GetInstance
{
get
{
if (Instance == null)
{
Instance = FindObjectOfType<PlayFabControllerPrefab>();
monoBehaviour = FindObjectOfType<MonoBehaviour>();
}
return Instance;
}
}
/// <summary>
/// Awakes the singleton.method
/// </summary>
public void AwakeSingleton()
{
// if the singleton hasn't been initialized yet
if (Equals(SetDontDestroyOnLoad, true))
{
if (!Equals(Instance, null) && !Equals(Instance, this))
{
if (Instance.DebugMode)
Debug.LogError("Duplicate singleton " + this.gameObject + " created; destroying it now");
Destroy(gameObject);
}
else {
DontDestroyOnLoad(gameObject);
}
}
else {
Instance = this;
monoBehaviour = GetComponent<MonoBehaviour>();
}
OnSetDebugMode = DebugMode;
}
#endregion
#region Playfab Calls
private void OnDisplayName(UpdateUserTitleDisplayNameResult result)
{
if (Instance.DebugMode)
Debug.Log(result.DisplayName + " is your new display name");
}
private void OnRegisterSuccess(RegisterPlayFabUserResult result)
{
if (Instance.DebugMode)
{
Debug.Log("OnRegisterSuccess:Congratulations, you made your first successful API call!");
}
}
private void OnLoginSuccess(LoginResult result)
{
myID = result.PlayFabId;
UserName.text = result.InfoResultPayload.AccountInfo.Username ?? result.PlayFabId;
isPlayerLoggedIn = true;
//Show our next screen if we logged in successfully.
Show2FAPanel();
CheckIfLoginPanelExists(false);
CheckIfLoggedinPanelExists(true);
if (Instance.DebugMode)
{
Debug.Log("OnLoginSuccess: Congratulations, you made your first successful API call! Logged in = " + isPlayerLoggedIn);
Debug.LogFormat("Logged In as: {0}", result.PlayFabId);
}
}
private void OnPlayFabError(PlayFabError error)
{
//There are more cases which can be caught, below are some
//of the basic ones.
switch (error.Error)
{
case PlayFabErrorCode.InvalidUsername:
case PlayFabErrorCode.InvalidEmailAddress:
case PlayFabErrorCode.InvalidPassword:
case PlayFabErrorCode.InvalidUsernameOrPassword:
case PlayFabErrorCode.InvalidEmailOrPassword:
StatusText.text = "Invalid Email or Password";
break;
case PlayFabErrorCode.UserAlreadyAdded:
RecoverySendPanel.SetActive(true);
RecoveryNewPassPanel.SetActive(false);
break;
case PlayFabErrorCode.AccountNotFound:
case PlayFabErrorCode.RegistrationIncomplete:
RegisterPanel.SetActive(true);
LoginPanel.SetActive(false);
LoggedinPanel.SetActive(false);
return;
case PlayFabErrorCode.TwoFactorAuthenticationTokenRequired:
TwoFactorAuthenticationPanel.SetActive(true);
break;
default:
StatusText.text = error.GenerateErrorReport();
break;
}
CheckIfLoginPanelExists(true);
CheckIfLoggedinPanelExists(false);
CheckIfRecoverySendPanelExists(false);
CheckIfRecoveryNewPassPanelExists(false);
CheckIfRegisterPanelExists(false);
CheckIfChangePassPanelExists(false);
CheckIfDevSettingsPanelExists(false);
CheckIfLeaderboadPanelExists(false);
isPlayerLoggedIn = false;
//Also report to debug console, this is optional.
if (Instance.DebugMode)
{
Debug.Log(error.Error);
Debug.LogError(error.GenerateErrorReport());
Debug.LogFormat("Is Player Logged in: {0}", isPlayerLoggedIn);
}
var registerRequest = new RegisterPlayFabUserRequest { Email = email, Password = password, Username = userName };
PlayFabClientAPI.RegisterPlayFabUser(registerRequest, OnRegisterSuccess, OnPlayFabError);
}
#endregion
#region Twitch
private void OnLoginWithTwitchClicked() {
}
#endregion
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static object _lock = new object();
public static T Instance
{
get
{
if (applicationIsQuitting) {
return null;
}
lock(_lock)
{
if (_instance == null)
{
_instance = (T) FindObjectOfType(typeof(T));
if ( FindObjectsOfType(typeof(T)).Length > 1 )
{
return _instance;
}
if (_instance == null)
{
GameObject singleton = new GameObject();
_instance = singleton.AddComponent<T>();
singleton.name = "(singleton) "+ typeof(T).ToString();
DontDestroyOnLoad(singleton);
}
}
return _instance;
}
}
}
private static bool applicationIsQuitting = false;
public void OnDestroy () {
applicationIsQuitting = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment