Skip to content

Instantly share code, notes, and snippets.

@ZeredaGames
Last active March 7, 2019 18:58
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/c639226ed15f60f397c415d8048c0ac5 to your computer and use it in GitHub Desktop.
Save ZeredaGames/c639226ed15f60f397c415d8048c0ac5 to your computer and use it in GitHub Desktop.
Building Upon the Playfab examples and the tutorials by InfoGamers.
using UnityEngine;
using System.Collections;
public class AppQuit : MonoBehaviour, IQuittable {
public void OnQuit() {
Debug.Log ("AppQuit.Quit");
Application.Quit ();
}
}
#region Licencing
/*
ZeredaGamesEngine
Author:
Zereda Games
Thamas Bell : thamasbell@hotmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
This permission notice shall be included in all copies or substantial portions of the Software diriving from this software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#endregion
#region using
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
#endregion
#region Script
namespace ZeredaGamesEngine.Core.GeneralScripts
{
/// <summary>
/// Click to load async.
/// </summary>
#region Attributes
[System.Serializable]
#endregion
public class ClickToLoadAsync : MonoBehaviour
{
public GameObject LoadingPanel;
private static Image loadingBar;
private AsyncOperation async;
/// <summary>
/// The autoload next level. If set to true, scrip will autoload next level;
/// </summary>
[Tooltip ("If Set to true, script will load next scene on first update method.")]
public bool AutoloadNextLevel;
/// <summary>
/// Add a wait timer.
/// </summary>
[Tooltip ("If Set to true, it overrides the Auto Load Next Level.")]
public bool AddWaitTimer;
/// <summary>
/// The time to wait. (Test in real world seconds not scaled time)
/// </summary>
[Tooltip ("When AddWaitTimer is set to true, how long until this script autoloads next level")]
public float WaitTime;
[Tooltip ("Used to Reset To default at runtime for testing.")]
public bool DisableAll;
/// <summary>
/// The Image used to fade a scene in or out.
/// </summary>
[Tooltip ("The Image used to fade a scene in or out.")]
public Image FadeImage;
/// <summary>
/// For fade panels after splash screens are over, how long it fades to alpha 0.
/// </summary>
[Tooltip ("For fade panels after splash screens are over, how long it fades to alpha 0.")]
public float FadeOutLength;
/// <summary>
/// For fade panels after splash screens are over, how long it fades to alpha 1.
/// </summary>
[Tooltip ("For fade panels after splash screens are over, how long it fades to alpha 1.")]
public float FadeInLength;
/// <summary>
/// When true debug logs desplay in the console otherwise thy don't.
/// </summary>
public static bool DebugMode;
/// <summary>
/// The current alpha. Used for the FadeImage.
/// </summary>
public static float curAlpha;
void Update ()
{
if (AddWaitTimer || AutoloadNextLevel || WaitTime <= 0.001f) {
DisableAll = false;
} else if (DisableAll) {
WaitTime = 0;
AddWaitTimer = false;
AutoloadNextLevel = false;
} else {
if (WaitTime <= 0.001f) {
AddWaitTimer = true;
}
if (AddWaitTimer) {
AutoloadNextLevel = true;
}
if (AutoloadNextLevel && AddWaitTimer) {
StartCoroutine (LoadLevelAfterTimeWithAsync());
return;
}
if (AutoloadNextLevel && !AddWaitTimer) {
SceneManager.LoadScene (SceneManager.GetActiveScene ().buildIndex + 1);
}
}
}
public void ClickButtonAsync (int level)
{
LoadingPanel.gameObject.SetActive (true);
loadingBar = GameObject.Find ("FillerImage").GetComponent<Image> ();
StartCoroutine (LoadLevelWithBar (level));
}
/// <summary>
/// Activates the game object.
/// </summary>
/// <param name="gameObject">Game object.</param>
public void ActivateGameObject (GameObject gameObject)
{
gameObject.SetActive (true);
}
/// <summary>
/// Deactivates the game object.
/// </summary>
/// <param name="gameObject">Game object.</param>
public void DeactivateGameObject (GameObject gameObject)
{
gameObject.SetActive (false);
}
/// <summary>
/// Loads the level. Simple Direct Method.
/// </summary>
/// <param name="value">Value.</param>
public void LoadLevel (string value)
{
SceneManager.LoadScene (value);
}
/// <summary>
/// Loads the level. Simple Direct Method.
/// </summary>
/// <param name="value">Value.</param>
public void LoadLevel (int value)
{
SceneManager.LoadScene (value);
}
/// <summary>
/// Loads the next level. Simple Direct Method.
/// </summary>
/// <param name="currentScene">Current scene.</param>
public void LoadNextLevel (int currentScene)
{
SceneManager.LoadScene (currentScene + 1);
}
/// <summary>
/// Public button Function.
/// </summary>
public void LoadNextScene ()
{
SceneManager.LoadScene (SceneManager.GetActiveScene ().buildIndex + 1);
}
/// <summary>
/// Loads the next scene with async.
/// </summary>
public void LoadNextSceneWithAsync ()
{
LoadLevelWithBar (SceneManager.GetActiveScene ().buildIndex + 1);
}
/// <summary>
/// Fades out the FadeImage.
/// </summary>
public void FadeOut ()
{
FadeImage.CrossFadeAlpha (0.0f, FadeOutLength, false);
}
/// <summary>
/// Fades in the FadeImage.
/// </summary>
public void FadeIn ()
{
FadeImage.CrossFadeAlpha (1.0f, FadeInLength, false);
}
/// <summary>
/// Loads the level with bar.
/// </summary>
/// <returns>The level with bar.</returns>
/// <param name="level">Level.</param>
public IEnumerator LoadLevelWithBar (int level)
{
GameObject loadingPanel = GameObject.FindObjectOfType<Canvas>().gameObject;
Image loadingBar = loadingPanel.transform.Find("Filler").GetComponent<Image>();
async = SceneManager.LoadSceneAsync (level);
while (!async.isDone) {
loadingBar.fillAmount = async.progress;
yield return null;
}
if (async.isDone) {
LoadingPanel.gameObject.SetActive (false);
}
}
/// <summary>
/// Loads the level with bar.
/// </summary>
/// <returns>The level with bar.</returns>
/// <param name="sceneName">Scene name.</param>
public IEnumerator LoadLevelWithBar (string sceneName)
{
LoadingPanel.SetActive(true);
Image loadingBar = LoadingPanel.transform.Find ("Filler").GetComponent<Image> ();
async = SceneManager.LoadSceneAsync (sceneName);
while (!async.isDone) {
loadingBar.fillAmount = async.progress;
yield return null;
}
if (async.isDone) {
LoadingPanel.SetActive (false);
}
}
/// <summary>
/// Loads the level after time. Time set by WaitTime variable. Simple Direct Method.
/// </summary>
/// <returns>The level after time.</returns>
public IEnumerator LoadLevelAfterTime ()
{
yield return new WaitForSecondsRealtime (WaitTime);
SceneManager.LoadScene (SceneManager.GetActiveScene ().buildIndex + 1);
}
/// <summary>
/// Loads the level after time with async.
/// </summary>
/// <returns>The level after time with async.</returns>
public IEnumerator LoadLevelAfterTimeWithAsync ()
{
yield return new WaitForSecondsRealtime (WaitTime);
LoadLevelWithBar (SceneManager.GetActiveScene ().buildIndex + 1);
}
}
}
#endregion
using UnityEngine;
using System.Collections.Generic;
[RequireComponent(typeof(AudioSource))]
public class FlexibleMusicManager : MonoBehaviour
{
#region Public Inspector Attributes
[Tooltip("If you want to get the mater volume from the player pref's set to true.")]
public bool
UseZGMasterVolume = true;
[Tooltip("Clips to play")]
public List<AudioClip>
playList;
[Tooltip("Keep playing this clip till clip is changed")]
public bool
repeat = false;
[Tooltip("When clip is done, go to next clip")]
public bool
autoAdvance = true;
[Tooltip("When end of playlist is reached, go back to start on advance")]
public bool
recycle = true;
[Tooltip("Begin playing first clip as soon as the MusicManager instantiates")]
public bool
playOnAwake = false;
[Tooltip("If nonzero, fade in on resume from pause or change track from middle of song for that many seconds")]
[Range(0f, 10f)]
public float
fadeInTime = 0.5f;
[Tooltip("If nonzero, fade out on pause or change track from middle of song for that many seconds")]
[Range(0f, 10f)]
public float
fadeOutTime = 1f;
[Tooltip("Volume control")]
[Range(0f, 1f)]
public float
volume = 0.5f;
[Tooltip("If true, on awake, load audioclips from resources directories into playlist")]
public bool
loadFromResources = true;
[Tooltip("If true, use as a Singleton class and don't destroy when scene is changed")]
public bool
dontDestroyOnLoad = true;
[Tooltip("Get Set on awake, but i wanted to access it from other scripts and i didnt want to have it static as i have multiple players in my snene's.")]
public AudioSource
audioSource;
#endregion
#region Public Scripted Setup
/// <summary>
/// Remove all clips from playlist
/// </summary>
public void ClearPlayList ()
{
playList.Clear ();
}
/// <summary>
/// Add a clip to the end of the playlist
/// </summary>
/// <param name="clip"></param>
public void AddToPlayList (AudioClip clip)
{
playList.Add (clip);
}
/// <summary>
/// Remove selected track from playlist (0 is first track)
/// </summary>
/// <param name="index"></param>
public void RemoveFromPlayList (int index)
{
playList.RemoveAt (index);
}
/// <summary>
/// Load given clip from resources folder(s) into playlist
/// </summary>
/// <param name="name"></param>
/// <returns>False if clip could not be loaded</returns>
public bool LoadClipFromResources (string name)
{
AudioClip clip = Resources.Load<AudioClip> (name);
if (clip) {
playList.Add (clip);
return true;
}
return false;
}
/// <summary>
/// Load all clips in resources folders into playlist, but without duplication
/// </summary>
/// <param name="path">optional subfolder of resources folder</param>
/// <returns>Number of unique clips added to playlist</returns>
public int LoadClipsFromResources (string path="")
{
AudioClip[] clips = Resources.LoadAll<AudioClip> (path);
int count = 0;
foreach (AudioClip clip in clips) {
if (!playList.Contains (clip)) {
count++;
playList.Add (clip);
}
}
return count;
}
/// <summary>
/// Get the audioclip at specified track in playlist (0 is first track)
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public AudioClip GetPlayListClip (int index)
{
if (index >= 0 && index < GetPlayListLength ()) {
return playList [index];
} else {
return null;
}
}
/// <summary>
/// Get the number of tracks in the playlist
/// </summary>
/// <returns></returns>
public int GetPlayListLength ()
{
return playList.Count;
}
/// <summary>
/// Set the fade-in time when resuming from pause
/// </summary>
/// <param name="time"></param>
public void SetFadeIn (float time)
{
if (time < 0 || time > 10) {
throw new UnityException ("Fade in time out of range: " + time);
}
fadeInTime = time;
}
/// <summary>
/// Set the fade-out time when pausing or stopping in the middle of a clip
/// </summary>
/// <param name="time"></param>
public void SetFadeOut (float time)
{
if (time < 0 || time > 10) {
throw new UnityException ("Fade out time out of range: " + time);
}
fadeOutTime = time;
}
/// <summary>
/// Adjust the volume control, from 0 to 1 (use 1 for "turn it up to eleven")
/// </summary>
/// <param name="amount"></param>
public void SetVolume (float amount)
{
volume = Mathf.Clamp (amount, 0, 1);
}
/// <summary>
/// Set autoadvance (like a CD player, next track when this track finishes),
/// only works if not repeating current track.
/// </summary>
public void AutoAdvance ()
{
autoAdvance = true;
}
/// <summary>
/// Unset autoadvance, stop playing when track ends
/// </summary>
public void NoAutoAdvance ()
{
autoAdvance = false;
}
/// <summary>
/// Repeat current track until manually changed
/// </summary>
public void Repeat ()
{
repeat = true;
}
/// <summary>
/// Don't repeat track--advance or stop when track is done
/// </summary>
public void NoRepeat ()
{
repeat = false;
}
/// <summary>
/// Repeat playlist from beginning when end is reached
/// </summary>
public void Recycle ()
{
recycle = true;
}
/// <summary>
/// Stop playing when end of playlist is reached
/// </summary>
public void NoRecycle ()
{
recycle = false;
}
#endregion
#region Public Controls
/// <summary>
/// Toggle between playing and pausing of current track
/// </summary>
public void PlayPauseToggle ()
{
if (!IsPlaying ()) {
Play ();
} else {
Pause ();
}
}
/// <summary>
/// Toggle the Repeat (loop this track) flag
/// </summary>
public void ToggleRepeat ()
{
if (repeat) {
NoRepeat ();
} else {
Repeat ();
}
}
/// <summary>
/// Toggle the Recycle (loop the whole playlist) flag
/// </summary>
public void ToggleRecycle ()
{
if (recycle) {
NoRecycle ();
} else {
Recycle ();
}
}
/// <summary>
/// Increment the volume
/// </summary>
public void VolumeUp (float amount = 0.05f)
{
SetVolume (volume + amount);
}
/// <summary>
/// Decrement the volume
/// </summary>
public void VolumeDown (float amount = 0.05f)
{
SetVolume (volume - amount);
}
/// <summary>
/// Toggle between muting and playing at last-set volume
/// </summary>
public void ToggleMute ()
{
if (saveVolume < 0) {
SendControlMessage (Message.MusicManager_Mute);
saveVolume = volume;
SetVolume (0);
} else {
SendControlMessage (Message.MusicManager_UnMute);
SetVolume (saveVolume);
saveVolume = -1;
}
}
/// <summary>
/// Start playing, or resume from pause
/// </summary>
public void Play ()
{
SendControlMessage (Message.MusicManager_Play);
if (!IsPlaying ()) {
if (IsPaused ()) {
ResumeFromPause ();
audioSource.time = saveTime;
} else {
saveTime = 0;
Rewind ();
ResumeFromPause ();
audioSource.time = 0;
}
}
}
/// <summary>
/// Stop playing, but don't lose place in clip
/// </summary>
public void Pause ()
{
SendControlMessage (Message.MusicManager_Pause);
saveTime = 0;
if (IsPlaying ()) {
isPlaying = false;
Fade (volume, 0, fadeOutTime);
saveTime = audioSource.time;
}
}
/// <summary>
/// Go back to beginning of playlist
/// </summary>
public void Rewind ()
{
if (IsPlaying ()) {
Pause ();
SetTrack (0);
Play ();
} else {
SetTrack (0);
Pause ();
}
}
/// <summary>
/// Go back to beginning of clip
/// </summary>
public void RewindClip ()
{
if (IsPlaying ()) {
Pause ();
audioSource.time = 0;
Play ();
} else {
audioSource.time = 0;
Pause ();
}
}
/// <summary>
/// Stop playing and rewind to beginning of playlist
/// </summary>
public void Stop ()
{
Pause ();
Rewind ();
}
/// <summary>
/// Stop playing and rewind to beginning of clip
/// </summary>
public void StopClip ()
{
Pause ();
Invoke ("RewindClip", fadeOutTime);
}
/// <summary>
/// Advance to next song on playlist.
/// </summary>
public void Next ()
{
if (IsPlaying ()) {
Pause ();
SetTrack (NextTrack ());
Play ();
} else {
SetTrack (NextTrack ());
Pause ();
}
}
/// <summary>
/// Go back to previous song on playlist
/// </summary>
public void Previous ()
{
if (IsPlaying ()) {
Pause ();
SetTrack (PreviousTrack ());
Play ();
} else {
SetTrack (PreviousTrack ());
Pause ();
}
}
/// <summary>
/// Advance a bit in the song
/// </summary>
/// <param name="seconds"></param>
public void MoveForward (float seconds = 10f)
{
if (IsPlaying ()) {
Pause ();
if (audioSource.clip) {
audioSource.time = Mathf.Clamp (audioSource.time + seconds, 0, audioSource.clip.length);
}
Play ();
} else {
if (audioSource.clip) {
audioSource.time = Mathf.Clamp (audioSource.time + seconds, 0, audioSource.clip.length);
}
}
}
/// <summary>
/// Go back a bit in the song
/// </summary>
/// <param name="seconds"></param>
public void MoveBackward (float seconds = 10f)
{
if (IsPlaying ()) {
Pause ();
if (audioSource.clip) {
audioSource.time = Mathf.Clamp (audioSource.time - seconds, 0, audioSource.clip.length);
}
Play ();
} else {
if (audioSource.clip) {
audioSource.time = Mathf.Clamp (audioSource.time - seconds, 0, audioSource.clip.length);
}
}
}
/// <summary>
/// Reorder the playlist randomly
/// </summary>
public void Shuffle ()
{
if (IsPlaying ()) {
Stop ();
//reorder playlist
Randomize (playList);
Play ();
} else if (IsPaused ()) {
Stop ();
//reorder playlist
Randomize (playList);
} else {
Randomize (playList);
}
}
public void ToggleRecycleOther ()
{
recycle = ! recycle;
}
public void ToggleRepeatOther ()
{
repeat = ! repeat;
}
public void ToggleAutoAdvance ()
{
autoAdvance = ! autoAdvance;
}
public static List<AudioClip> AddToPlayList (List<AudioClip>clips, AudioClip clip)
{
if (!clips.Contains (clip)) {
clips.Add (clip);
}
return clips;
}
#endregion
#region Public Queries
/// <summary>
/// Track number playing (from 0 to number of tracks - 1)
/// </summary>
/// <returns></returns>
public int CurrentTrackNumber ()
{
return trackNumber;
}
/// <summary>
/// Audio clip now playing (even if paused)
/// </summary>
/// <returns></returns>
public AudioClip NowPlaying ()
{
return playList [trackNumber];
}
/// <summary>
/// True if there is a current clip and it is not paused
/// </summary>
/// <returns></returns>
public bool IsPlaying ()
{
return isPlaying;
}
/// <summary>
/// True if there is a current clip and it is paused
/// </summary>
/// <returns></returns>
public bool IsPaused ()
{
return !IsPlaying () && CurrentTrackNumber () >= 0;
}
/// <summary>
/// Time into the current clip
/// </summary>
/// <returns></returns>
public float TimeInSeconds ()
{
return audioSource.time;
}
/// <summary>
/// Length of the current clip, or 0 if no clip
/// </summary>
/// <returns></returns>
public float LengthInSeconds ()
{
if (!audioSource.clip) {
return 0;
}
return audioSource.clip.length;
}
#endregion
#region Internal Manager State
int trackNumber = -1; //negative means no active track
bool isPlaying = false;
float fadeStartVolume;
float fadeEndVolume;
float fadeTime = 0;
float fadeStartTime;
float saveVolume = -1;
float saveTime = 0;
#endregion
#region Internal Singleton
private static FlexibleMusicManager _instance;
public static FlexibleMusicManager instance {
get {
if (_instance == null) {//in case not awake yet
_instance = FindObjectOfType<FlexibleMusicManager> ();
}
return _instance;
}
}
void Awake ()
{
// if the singleton hasn't been initialized yet
if (dontDestroyOnLoad) {
if (_instance != null && _instance != this) {
Debug.LogError ("Duplicate singleton " + this.gameObject + " created; destroying it now");
Destroy (this.gameObject);
}
if (_instance != this) {
_instance = this;
DontDestroyOnLoad (this.gameObject);
}
} else {
_instance = this;
}
}
#endregion
#region Internal Methods
// Use this for initialization
void Start ()
{
if (UseZGMasterVolume)
volume = PlayerPrefs.GetFloat ("MasterVolume");
audioSource = gameObject.GetComponent<AudioSource> ();
audioSource.loop = repeat && !autoAdvance;
audioSource.playOnAwake = false;
audioSource.volume = volume;
if (loadFromResources) {
LoadClipsFromResources ();
}
Rewind ();
if (playOnAwake) {
Play ();
}
}
// Update is called once per frame
void Update ()
{
if (fadeTime > 0) {
SetFadeVolume ();
} else {
audioSource.volume = volume;
}
if (isPlaying && !audioSource.isPlaying && audioSource.time == 0) {
ClipFinished ();
}
audioSource.loop = repeat;
}
void SetFadeVolume ()
{
fadeEndVolume = Mathf.Clamp (fadeEndVolume, 0, volume);//in case volume control adjusted
//during fade
float t = (Time.time - fadeStartTime) / fadeTime;
if (t >= 1) {
fadeTime = 0;
if (fadeEndVolume == 0) {
audioSource.Stop ();
audioSource.time = saveTime;
}
audioSource.volume = volume;
} else {
audioSource.volume = (1 - t) * fadeStartVolume + t * fadeEndVolume;
}
}
void ClipFinished ()
{
if (autoAdvance) {
Next ();
} else {
Pause ();
}
}
void ResumeFromPause ()
{
if (CurrentTrackNumber () >= 0) {
isPlaying = true;
Fade (0, volume, fadeInTime);
}
}
void SetTrack (int trackNum)
{
if (CurrentTrackNumber () != trackNum) {
SendControlMessage (Message.MusicManager_ChangeTrack);
}
saveTime = 0;
if (GetPlayListLength () == 0) {
trackNumber = -1;
} else if (trackNum >= 0 && trackNum < GetPlayListLength ()) {
trackNumber = trackNum;
} else if (recycle) {
trackNumber = (trackNum % GetPlayListLength () + GetPlayListLength ()) % GetPlayListLength ();
} else {
trackNumber = -1;
}
}
int NextTrack ()
{
int trackNum = trackNumber + 1;
if (trackNum >= 0 && trackNum < GetPlayListLength ()) {
return trackNum;
} else if (recycle) {
return (trackNum % GetPlayListLength () + GetPlayListLength ()) % GetPlayListLength ();
} else {
Stop ();
return -1;
}
}
int PreviousTrack ()
{
int trackNum = trackNumber - 1;
if (trackNum >= 0 && trackNum < GetPlayListLength ()) {
return trackNum;
} else if (recycle) {
return (trackNum % GetPlayListLength () + GetPlayListLength ()) % GetPlayListLength ();
} else {
return -1;
}
}
void Fade (float startVolume, float endVolume, float time)
{
if (audioSource.isPlaying) {
fadeStartTime = Time.time;
fadeStartVolume = startVolume;
fadeEndVolume = endVolume;
fadeTime = time;
audioSource.volume = startVolume;
if (startVolume == 0) {
audioSource.Stop ();
audioSource.clip = NowPlaying ();
audioSource.Play ();
}
} else {
if (startVolume == 0) {
audioSource.clip = NowPlaying ();
audioSource.volume = endVolume;
audioSource.Play ();
}
}
}
void Randomize (List<AudioClip> list)
{
for (int i = 0; i < list.Count - 1 /*because random(a,a) is inclusive*/; i++) {
int j = Random.Range (i + 1, list.Count);
AudioClip tmp = list [i];
list [i] = list [j];
list [j] = tmp;
}
}
#endregion
#region Messages
[Tooltip("Send control messages like MusicManager_Play, etc., to scripts in user-supplied parent game objects (advanced)")]
public bool
sendControlMessagesUpward = false;
[Tooltip("Send control messages like MusicManager_Play, etc., to scripts in user-supplied child game objects (advanced)")]
public bool
sendControlMessagesDownward = false;
[Tooltip("Send control messages like MusicManager_Play, etc., to user-supplied scripts in this game object (advanced)")]
public bool
sendControlMessagesToThisGameObject = true;
[Tooltip("Log control messages like MusicManager_Play, etc., to the Unity console or the executable's log file")]
public bool
logControlMessages = false;
void SendControlMessage (Message message)
{
string message_string = message.ToString ();
if (sendControlMessagesUpward) {
SendMessageUpwards (message_string, SendMessageOptions.DontRequireReceiver);
}
if (sendControlMessagesDownward) {
BroadcastMessage (message_string, SendMessageOptions.DontRequireReceiver);
}
if (sendControlMessagesToThisGameObject) {
SendMessage (message_string, SendMessageOptions.DontRequireReceiver);
}
if (logControlMessages) {
Debug.Log ("Control Message: \"" + message_string + "\"");
}
}
private enum Message
{
MusicManager_Play,
MusicManager_Pause,
MusicManager_Mute,
MusicManager_UnMute,
MusicManager_ChangeTrack
}
#endregion
}
public interface IQuittable {
void OnQuit ();
}
public interface IPausable {
void OnUnPause ();
void OnPause ();
}
public interface IOptionable
{
void OnOptions (GameObject sceneGUIObject);
void OnClose (GameObject sceneGUIObject);
void OnSaveAndExit ();
void OnSaveGraphics (float value);
void OnSaveVolume (float value);
/// <summary>
/// Sets the default. (Use this for options menu to set the game settings to default)
/// </summary>
string OnGetDefault ();
}
public interface IDamagable
{
void OnDamage (float value);
}
public interface IHealable
{
void OnHeal (float Value);
}
public interface IMenueableGUI
{
void OnGUI ();
}
public interface IGUI
{
void OnGUI ();
}
public interface ICallable
{
void OnCall ();
}
public interface IDestroy
{
void OnDestroy (GameObject obj);
}
public interface IEnableable
{
void OnEnable (GameObject obj);
}
public interface IDisableable
{
void OnDisable (GameObject obj);
}
public interface IMusicable
{
void OnLoadSongList (string file);
void OnPlayNextSong ();
void OnSaveVolume (float value);
void OnPauseMusic ();
void OnUnpauseMusic ();
void OnPlayMusic (AudioClip a, float fadeOut, float fadeIn);
void OnStopMusic (float fadeOut);
void OnPlay (string name, float fadeOut = 0f, float fadeIn = 0f);
void OnPlay (AudioClip clip, float fadeOut = 0f, float fadeIn = 0f);
void OnSetLoop (bool t);
void OnSetDefault ();
}
public interface IEquatable<T>
{
bool Equals (T obj);
}
#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 ScriptClass 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 ScriptClass GetInstance
{
get
{
if (Instance == null)
{
Instance = FindObjectOfType<ScriptClass>();
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
/// <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;
}
}
#region About
/**
* Company: InfoGamer, ZeredaGames
* Product: Player Login with Playfab
* Bundle Version: V1.0.0.1.0 //Build Version, Major Update, Minor Update, Revision, Patch
* PlayFabController.cs
* Created by: InfoGamer, Revision by ZeredaGames
* Created on: (3/3/2019)
*/
#endregion
#region Licencing
#endregion
#region using
#region Unity
using UnityEngine;
using UnityEngine.UI;
#endregion
#endregion
public class LearderboardListing : MonoBehaviour
{
public Text playerNameText;
public Text playerScoreText;
public Text playerRank;
}
using UnityEngine;
using System.Collections;
public class LO_LaunchURL : MonoBehaviour {
public void urlLinkOrWeb(string URL)
{
Application.OpenURL(URL);
}
}
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
public class LO_LoadingScreen : MonoBehaviour
{
private static LO_LoadingScreen instance = null;
[Header("RESOURCES")]
public CanvasGroup canvasAlpha;
public Text status;
public Text title;
public Text titleDescription;
public Slider progressBar;
public static string prefabName = "Stock_Style";
[Header("RANDOM HINTS")]
public Text hintsText;
public List<string> HintList = new List<string>();
public bool changeHintWithTimer;
public float hintTimerValue = 5;
// [Range(0.1f, 1)] public float hintFadingSpeed = 1;
private float htvTimer;
[Header("RANDOM IMAGES")]
public Image imageObject;
public Animator fadingAnimator;
public List<Sprite> ImageList = new List<Sprite>();
public bool changeImageWithTimer;
public float imageTimerValue = 5;
[Range(0.1f, 5)] public float imageFadingSpeed = 1;
private float itvTimer;
[Header("PRESS ANY KEY (WIP)")]
public Animator objectAnimator;
private bool isAnimPlayed = false;
[Header("VIRTUAL LOADING")]
[Tooltip("Second(s)")]
public float virtualLoadingTimer = 5;
private float vltTimer;
[Header("SETTINGS")]
public bool enableVirtualLoading = false;
public bool enableTitleDesc = true;
public bool enableRandomHints = true;
public bool enableRandomImages = true;
public bool enablePressAnyKey = true;
public string titleText;
public string titleDescText;
public float fadingAnimationSpeed = 2.0f;
private bool isHintAlphaZero;
void Start()
{
// If this is disabled, then disable Title Description object
if (enableTitleDesc == false)
{
titleDescription.enabled = false;
}
// If this is enabled, generate random hints
if (enableRandomHints == true)
{
string hintChose = HintList[Random.Range(0, HintList.Count)];
hintsText.text = hintChose;
}
// If this is enabled, generate random images
if (enableRandomImages == true)
{
Sprite imageChose = ImageList[Random.Range(0, ImageList.Count)];
imageObject.sprite = imageChose;
}
// Set up title text
title.text = titleText;
titleDescription.text = titleDescText;
// Set up Random Image fading anim speed
fadingAnimator.speed = imageFadingSpeed;
// fadingAnimator.SetFloat("Fade Out", imageFadingSpeed);
}
// Scene loading process
private AsyncOperation loadingProcess;
// Load a new scene
public static void LoadScene(string sceneName)
{
// If there isn't a LoadingScreen, then create a new one
instance = Instantiate(Resources.Load<GameObject>(prefabName)).GetComponent<LO_LoadingScreen>();
// Don't destroy loading screen while it's loading
DontDestroyOnLoad(instance.gameObject);
// Enable loading screen
instance.gameObject.SetActive(true);
// Start loading between scenes
instance.loadingProcess = SceneManager.LoadSceneAsync(sceneName);
// Don't allow scene switching
instance.loadingProcess.allowSceneActivation = false;
}
void Awake()
{
// Set loading screen invisible at first (panel alpha color)
canvasAlpha.alpha = 0f;
}
void Update()
{
try
{
// Update loading status
progressBar.value = loadingProcess.progress;
status.text = Mathf.Round(progressBar.value * 100f).ToString() + "%";
}
catch
{
Debug.Log("No progress bar");
}
// Do virtual loading if it's enabled --- and yes, a lot ifs...
if (enableVirtualLoading == true)
{
vltTimer += Time.deltaTime;
if (vltTimer >= virtualLoadingTimer && loadingProcess.isDone)
{
loadingProcess.allowSceneActivation = true;
canvasAlpha.alpha -= fadingAnimationSpeed * Time.deltaTime;
if (canvasAlpha.alpha <= 0)
{
Destroy(gameObject);
}
}
else
{
canvasAlpha.alpha += fadingAnimationSpeed * Time.deltaTime;
if (canvasAlpha.alpha >= 1 && vltTimer >= virtualLoadingTimer)
{
loadingProcess.allowSceneActivation = true;
}
}
}
else
{
// If loading is complete
if (loadingProcess.isDone && enablePressAnyKey == false)
{
// Fade out
canvasAlpha.alpha -= fadingAnimationSpeed * Time.deltaTime;
// If fade out is complete, then disable the object
if (canvasAlpha.alpha <= 0)
{
Destroy(gameObject);
}
}
else // If loading proccess isn't completed
{
// Start Fade in
canvasAlpha.alpha += fadingAnimationSpeed * Time.deltaTime;
// If loading screen is visible
if (canvasAlpha.alpha >= 1)
{
// We're good to go. New scene is on! :)
loadingProcess.allowSceneActivation = true;
}
}
// If loading is completed and PAK feature enabled, show Press Any Key panel
if (progressBar.value == 1 && enablePressAnyKey == true && isAnimPlayed == false)
{
objectAnimator.enabled = true;
objectAnimator.Play("PAK Fade-in");
isAnimPlayed = true;
}
}
// Check if random images are enabled
if (enableRandomImages == true)
{
itvTimer += Time.deltaTime;
if (itvTimer >= imageTimerValue && fadingAnimator.GetCurrentAnimatorStateInfo(0).IsName("Start"))
{
fadingAnimator.Play("Fade In");
}
else if (itvTimer >= imageTimerValue && fadingAnimator.GetCurrentAnimatorStateInfo(0).IsName("Fade Out"))
{
Sprite imageChose = ImageList[Random.Range(0, ImageList.Count)];
imageObject.sprite = imageChose;
itvTimer = 0.0f;
}
}
// Check if random hints are enabled
if (enableRandomHints == true)
{
htvTimer += Time.deltaTime;
if (htvTimer >= hintTimerValue && isHintAlphaZero == false)
{
string hintChose = HintList[Random.Range(0, HintList.Count)];
hintsText.text = hintChose;
htvTimer = 0.0f;
}
}
}
}
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class LO_LoadScene : MonoBehaviour
{
public void ChangeToScene (string sceneName)
{
LO_LoadingScreen.LoadScene(sceneName);
}
}
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class LO_LoadSceneTrigger : MonoBehaviour
{
[Header("SETTINGS")]
public bool onTriggerExit;
public bool onlyLoadWithTag;
[Header("STRINGS")]
public string objectTag;
public string sceneName;
public string prefabToLoad;
private void OnTriggerEnter(Collider other)
{
if(onlyLoadWithTag == true && onTriggerExit == false)
{
if (other.gameObject.tag == objectTag)
{
LO_LoadingScreen.prefabName = prefabToLoad;
LO_LoadingScreen.LoadScene(sceneName);
}
}
else if (onTriggerExit == false)
{
LO_LoadingScreen.prefabName = prefabToLoad;
LO_LoadingScreen.LoadScene(sceneName);
}
}
private void OnTriggerExit(Collider other)
{
if(onlyLoadWithTag == true && onTriggerExit == true)
{
if (other.gameObject.tag == objectTag)
{
LO_LoadingScreen.prefabName = prefabToLoad;
LO_LoadingScreen.LoadScene(sceneName);
}
}
else if (onTriggerExit == true)
{
LO_LoadingScreen.prefabName = prefabToLoad;
LO_LoadingScreen.LoadScene(sceneName);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LO_PressAnyKey : MonoBehaviour {
[Header("OBJECTS")]
public GameObject scriptObject;
public Animator animatorComponent;
void Start ()
{
animatorComponent.GetComponent<Animator>();
}
void Update ()
{
if (Input.anyKeyDown)
{
animatorComponent.Play ("PAK Fade-out");
Destroy (scriptObject);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LO_RadialSlider : MonoBehaviour {
[Header("OBJECTS")]
public Image sliderImage;
public Slider baseSlider;
private float currentValue = 0;
void Update ()
{
// baseSlider.value = currentValue / 100;
currentValue = baseSlider.value / 1;
// currentValue = Mathf.Round(sliderImage.fillAmount * 100) / 1f;
sliderImage.fillAmount = currentValue;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LO_SelectStyle : MonoBehaviour
{
public void SetStyle(string prefabToLoad)
{
LO_LoadingScreen.prefabName = prefabToLoad;
}
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;
using System;
public class Localizatron : Singleton<Localizatron> {
public Localizatron() {}
// Private features
private string _languagePath;
private string _currentLanguage;
private Dictionary<string,string> languageTable;
// Methods
public Dictionary<string, string> GetLanguageTable() {
return this.languageTable;
}
public bool SetLanguage(string language) {
if (Regex.IsMatch(language, @"^[a-z]{2}-[A-Z]{2}$")) {
this._currentLanguage = language;
this._languagePath = /*Settings.LANGUAGE_PATH +*/ this._currentLanguage /*+ Settings.LANGUAGE_EXTENSION*/;
this.languageTable = this.loadLanguageTable(this._languagePath);
Debug.Log ("[Localizatron] Locale loaded at: " + this._languagePath);
return true;
}
else {
return false;
}
}
public string GetCurrentLanguage() {
return this._currentLanguage;
}
public string Translate(string key) {
if (this.languageTable != null) {
if (this.languageTable.ContainsKey (key)) {
return this.languageTable [key];
} else {
return key;
}
} else
{
return key;
}
}
public Dictionary<string, string> loadLanguageTable(string fileName) {
try {
TextAsset file = Resources.Load("Localizatron/Locale/" + fileName) as TextAsset;
//Debug.Log(fileName);
//Debug.Log(file.name);
//StreamReader reader = new StreamReader(fileName);
//Debug.Log(file.name);
string languageFileContent = file.text;//reader.ReadToEnd();
//reader.Close();
Dictionary<string, string> languageDict = new Dictionary<string, string>();
Regex regexKey = new Regex(@"<key>(.*?)</key>");
Regex regexValue = new Regex(@"<value>(.*?)</value>");
MatchCollection keysMatchCollection = regexKey.Matches(languageFileContent);
MatchCollection valuesMatchCollection = regexValue.Matches(languageFileContent);
IEnumerator keysEnum = keysMatchCollection.GetEnumerator();
IEnumerator valuesEnum = valuesMatchCollection.GetEnumerator();
while(keysEnum.MoveNext()) {
valuesEnum.MoveNext();
languageDict.Add(keysEnum.Current.ToString().Replace("<key>", "").Replace("</key>", ""),
valuesEnum.Current.ToString().Replace("<value>", "").Replace("</value>", ""));
}
return languageDict;
}
catch(FileNotFoundException e) {
Debug.Log ( e.Message );
return null;
}
}
private void Init() {
// Set language to default
this.SetLanguage (Settings.LANGUAGE_DEFAULT);
}
void Awake () {
this.Init();
}
}
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.IO;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public enum CONTEXT {
FILES_MANAGER,
EDIT_FILE
}
public enum EDITOR_EVENT {
NONE,
ADD_ENTRY
}
public class LocalizatronEditor : EditorWindow {
protected static bool IS_DEBUG = true;
protected static List<string> langFiles;
protected string newFileName;
protected string selectedFile;
protected Dictionary<string, string> localeDict;
private CONTEXT _context = CONTEXT.FILES_MANAGER;
private static string logStream = "";
Queue<Action> guiEvents = new Queue<Action>();
[MenuItem ("Window/Localizatron")]
static void OpenLocalizationWindow() {
LocalizatronEditor.GetLocalizationFiles();
EditorWindow.GetWindow(typeof(LocalizatronEditor), false, "Localizatron");
}
void OnGUI() {
switch(this._context) {
case CONTEXT.FILES_MANAGER:
this.FileManagerWindow();
break;
case CONTEXT.EDIT_FILE:
this.EditFileWindow();
break;
}
if(LocalizatronEditor.IS_DEBUG) {
EditorGUILayout.TextArea(LocalizatronEditor.logStream, GUILayout.MaxHeight(50), GUILayout.MaxWidth(450), GUILayout.ExpandHeight(false));
}
}
void Update() {
while (guiEvents.Count > 0)
{
this.guiEvents.Dequeue().Invoke();
}
Repaint ();
}
public static void Log(string message) {
LocalizatronEditor.logStream = "[Localizatron " + DateTime.Now.ToString() + "]: " + message + "\n" + LocalizatronEditor.logStream;
}
protected static void GetLocalizationFiles() {
try {
LocalizatronEditor.langFiles = new List<string>();
if(!Directory.Exists(Settings.LANGUAGE_PATH + Path.DirectorySeparatorChar)) {
Directory.CreateDirectory(Settings.LANGUAGE_PATH + Path.DirectorySeparatorChar);
}
string[] paths = Directory.GetFiles(Settings.LANGUAGE_PATH);
foreach (string path in paths) {
if(path.Contains(Settings.LANGUAGE_EXTENSION) && !path.Contains(".meta")) {
LocalizatronEditor.langFiles.Add(path);
}
}
LocalizatronEditor.Log("Localization files loaded successfully!");
}
catch(Exception e) {
if(IS_DEBUG)
LocalizatronEditor.Log("Failed to inizialize files: " + e.Message);
}
}
protected static void SaveLocalizationFile(string fileName, string content) {
System.IO.File.WriteAllText(Application.dataPath + Settings.SAVING_LANGUAGE_PATH + fileName + Settings.LANGUAGE_EXTENSION, content);
LocalizatronEditor.Log("Localization files (" + fileName + ") saved!");
}
protected static void DeleteLocalizationFile(string filePath) {
System.IO.File.Delete(Application.dataPath + Settings.SAVING_LANGUAGE_PATH + Path.GetFileName(filePath));
LocalizatronEditor.Log("Localization files (" + Path.GetFileName(filePath) + ") deleted!");
}
protected void OnDeleteFileInFileManagerWindow(string entry) {
LocalizatronEditor.langFiles.Remove(entry);
LocalizatronEditor.DeleteLocalizationFile(entry);
}
protected Vector2 scrollPositionFileManager = Vector2.zero;
protected void FileManagerWindow() {
try {
EditorGUILayout.LabelField("Localization files", EditorStyles.boldLabel);
EditorGUILayout.Space();
EditorGUILayout.BeginScrollView(this.scrollPositionFileManager, GUILayout.MaxWidth(450), GUILayout.MaxHeight(450), GUILayout.ExpandHeight(false));
foreach(string entry in LocalizatronEditor.langFiles) {
EditorGUILayout.BeginHorizontal();
EditorGUILayout.BeginVertical();
EditorGUILayout.TextField(Path.GetFileName(entry).Replace(Settings.LANGUAGE_EXTENSION, ""));
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical();
if(GUILayout.Button("Delete", EditorStyles.miniButtonLeft, GUILayout.Width(45))){
OnDeleteFileInFileManagerWindow(entry);
}
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical();
if(GUILayout.Button("Edit", EditorStyles.miniButtonRight, GUILayout.Width(45))){
this.selectedFile = Path.GetFileName(entry).Replace(Settings.LANGUAGE_EXTENSION, "");
this.localeDict = this.inEditorLoadLanguageTable(Application.dataPath + Settings.SAVING_LANGUAGE_PATH + this.selectedFile + Settings.LANGUAGE_EXTENSION);
if(this.localeDict.Count == 0) {
this.localeDict.Add("Entry-" + DateTime.Now.Ticks, "");
}
this._context = CONTEXT.EDIT_FILE;
LocalizatronEditor.Log("Selected localization file: " + this.selectedFile);
}
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.BeginVertical();
this.newFileName = EditorGUILayout.TextField(this.newFileName);
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical();
if(GUILayout.Button("Add new localization file")){
if(this.newFileName != "" && this.newFileName != null) {
LocalizatronEditor.langFiles.Add(Settings.LANGUAGE_PATH + this.newFileName);
LocalizatronEditor.SaveLocalizationFile(this.newFileName, "<key></key><value></value>");
this.newFileName = "";
}
else {
LocalizatronEditor.Log("You cannot add an unnamed file!");
}
}
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndScrollView();
}
catch(Exception e) {
if(LocalizatronEditor.IS_DEBUG)
LocalizatronEditor.Log("Updated missing ref of deleted file");
EditorGUILayout.EndScrollView();
}
}
protected string fileContent;
protected Dictionary<string, string> finalContentDict = new Dictionary<string, string>();
protected Vector2 scrollPosition = Vector2.zero;
protected string keyFilter = "";
protected string valueFilter = "";
protected void EditFileWindow() {
try {
EditorGUILayout.LabelField("Editing locale: " + this.selectedFile, EditorStyles.boldLabel);
EditorGUILayout.Space();
this.scrollPosition = EditorGUILayout.BeginScrollView(this.scrollPosition, GUILayout.MaxWidth(450), GUILayout.MaxHeight(450), GUILayout.ExpandHeight(false));
EditorGUILayout.BeginHorizontal();
EditorGUILayout.BeginVertical();
EditorGUILayout.LabelField("Key Filter", EditorStyles.boldLabel);
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical();
this.keyFilter = EditorGUILayout.TextField(this.keyFilter);
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.BeginVertical();
EditorGUILayout.LabelField("Value Filter", EditorStyles.boldLabel);
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical();
this.valueFilter = EditorGUILayout.TextField(this.valueFilter);
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.BeginVertical();
EditorGUILayout.LabelField("Key", EditorStyles.boldLabel);
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical();
EditorGUILayout.LabelField("Value", EditorStyles.boldLabel);
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
if(this.localeDict == null) {
this.localeDict = this.inEditorLoadLanguageTable(Application.dataPath + Settings.SAVING_LANGUAGE_PATH + this.selectedFile + Settings.LANGUAGE_EXTENSION);
}
bool isFiltered = false;
foreach(KeyValuePair<string, string> pair in this.localeDict) {
string tmpKey = "", tmpValue = "";
if(this.keyFilter != "" || this.valueFilter != "") {
isFiltered = true;
if(this.keyFilter != "" && this.valueFilter != "") {
if(pair.Key.ToLower().Contains(this.keyFilter.ToLower()) && pair.Value.ToLower().Contains(this.valueFilter.ToLower())) {
EditorGUILayout.BeginHorizontal();
EditorGUILayout.BeginVertical();
tmpKey = EditorGUILayout.TextField(pair.Key);
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical();
tmpValue = EditorGUILayout.TextField(pair.Value);
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
}
}
else if(this.keyFilter != "") {
if(pair.Key.ToLower().Contains(this.keyFilter.ToLower())) {
EditorGUILayout.BeginHorizontal();
EditorGUILayout.BeginVertical();
tmpKey = EditorGUILayout.TextField(pair.Key);
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical();
tmpValue = EditorGUILayout.TextField(pair.Value);
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
}
}
else if(this.valueFilter != "") {
if(pair.Value.ToLower().Contains(this.valueFilter.ToLower())) {
EditorGUILayout.BeginHorizontal();
EditorGUILayout.BeginVertical();
tmpKey = EditorGUILayout.TextField(pair.Key);
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical();
tmpValue = EditorGUILayout.TextField(pair.Value);
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
}
}
}
else {
EditorGUILayout.BeginHorizontal();
EditorGUILayout.BeginVertical();
tmpKey = EditorGUILayout.TextField(pair.Key);
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical();
tmpValue = EditorGUILayout.TextField(pair.Value);
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
}
if(this.finalContentDict.ContainsKey(pair.Key)) {
this.finalContentDict.Remove(pair.Key);
}
if(tmpKey != "")
this.finalContentDict[tmpKey] = tmpValue;
}
if(!isFiltered)
this.localeDict = new Dictionary<string, string>(this.finalContentDict);
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.BeginVertical();
if(GUILayout.Button("Add entry")){
guiEvents.Enqueue(()=>
{
try {
this.localeDict.Add("Entry-" + DateTime.Now.Ticks , "");
}
catch(Exception e) {
if(LocalizatronEditor.IS_DEBUG)
LocalizatronEditor.Log(e.Message);
}
});
}
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.BeginVertical();
if(GUILayout.Button("< Back")){
this.selectedFile = "";
this.localeDict = null;
this.finalContentDict.Clear();
this._context = CONTEXT.FILES_MANAGER;
}
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical();
if(GUILayout.Button("Save locale")){
string finalContent = "";
foreach(KeyValuePair<string, string> kv in this.finalContentDict) {
finalContent += "<key>" + kv.Key + "</key><value>" + kv.Value + "</value>\n";
}
LocalizatronEditor.SaveLocalizationFile(this.selectedFile, finalContent);
}
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndScrollView();
}
catch(Exception e) {
if(LocalizatronEditor.IS_DEBUG)
LocalizatronEditor.Log (e.Message);
EditorGUILayout.EndScrollView();
}
}
public Dictionary<string, string> inEditorLoadLanguageTable(string fileName) {
try {
StreamReader reader = new StreamReader (fileName);
string languageFileContent = reader.ReadToEnd();
reader.Close();
Dictionary<string, string> languageDict = new Dictionary<string, string>();
Regex regexKey = new Regex(@"<key>(.*?)</key>");
Regex regexValue = new Regex(@"<value>(.*?)</value>");
MatchCollection keysMatchCollection = regexKey.Matches(languageFileContent);
MatchCollection valuesMatchCollection = regexValue.Matches(languageFileContent);
IEnumerator keysEnum = keysMatchCollection.GetEnumerator();
IEnumerator valuesEnum = valuesMatchCollection.GetEnumerator();
while(keysEnum.MoveNext()) {
valuesEnum.MoveNext();
languageDict.Add(keysEnum.Current.ToString().Replace("<key>", "").Replace("</key>", ""),
valuesEnum.Current.ToString().Replace("<value>", "").Replace("</value>", ""));
}
return languageDict;
}
catch(FileNotFoundException e) {
Debug.Log ( e.Message );
return null;
}
}
}
using UnityEngine;
using System.Collections;
public class LocalizatronExample : MonoBehaviour {
private float _screenMiddleX;
private float _screenMiddleY;
void Start() {
this._screenMiddleX = Screen.width / 2;
this._screenMiddleY = Screen.height / 2;
}
void OnGUI() {
if(GUI.Button(new Rect(10f, 10f, 50f, 22f), "it-IT")) {
Localizatron.Instance.SetLanguage("it-IT");
}
if(GUI.Button(new Rect(70f, 10f, 50f, 22f), "en-EN")) {
Localizatron.Instance.SetLanguage("en-EN");
}
GUI.Label(new Rect((this._screenMiddleX - 50f), (this._screenMiddleY - 11f), 100f, 22f), Localizatron.Instance.Translate("Hello World"));
}
}
using System.Collections;
using UnityEditor;
using UnityEngine;
/*
Not mine, this is terrably executed.. I'll fix it later..
*/
public class LooaderEditorWindow : EditorWindow {
private static LooaderEditorWindow instance = null;
[MenuItem("Tools/Looader/Create Looader Manager")]
static void CreateLooaderSystem()
{
instance = Instantiate(Resources.Load<GameObject>("Looader Manager")).GetComponent<LooaderEditorWindow>();
}
[MenuItem("Tools/Looader/Create Trigger Object")]
static void CreateTriggerObject()
{
instance = Instantiate(Resources.Load<GameObject>("Trigger Object")).GetComponent<LooaderEditorWindow>();
}
public static void OnCustomWindow()
{
EditorWindow.GetWindow(typeof(LooaderEditorWindow));
}
}
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class NowPlaying : MonoBehaviour {
public Text nowPlayingText;
void Update () {
if (FlexibleMusicManager.instance.CurrentTrackNumber() >= 0) {
string timeText = SecondsToMS(FlexibleMusicManager.instance.TimeInSeconds());
string lengthText = SecondsToMS(FlexibleMusicManager.instance.LengthInSeconds());
nowPlayingText.text = "" + (FlexibleMusicManager.instance.CurrentTrackNumber() + 1) + ". " +
FlexibleMusicManager.instance.NowPlaying().name
+ " (" + timeText + "/" + lengthText + ")" ;
}else {
nowPlayingText.text = "-----------------";
}
}
string SecondsToMS(float seconds) {
return string.Format("{0:D3}:{1:D2}", ((int)seconds)/60, ((int)seconds)%60);
}
}
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
public class PauseManager : MonoBehaviour {
[Tooltip("What Key do you want to use to pause the game?")]
public KeyCode PauseKey = KeyCode.Escape;
private bool isPaused = false;
[Tooltip("Animator on the pause canvas. 'Set's in start if not set here'")]
public Animator anim;
[Tooltip("This GameObject. 'Set's in start if not set here'")]
public PauseManager pausable;
[Tooltip("The Canvas the pause menu will display on.'")]
public Canvas pauseCanvas;
[Tooltip("What are all of your pausable objects? Has OnPause/OnUnPause + Dirives from IPausable")]
public Component[] pausableInterfaces;
[Tooltip("What are all of your quittable objects? Has OnQuit + Dirives from IQuitable")]
public Component[] quittableInterfaces;
[Tooltip("Tag on the pause canvas, if not set here.")]
public string pauseCanvasTag = "PauseCanvas";
private string debugMode;
void Awake()
{
if (Equals(pausable, null))
pausable = this;
if (Equals(pauseCanvas, null))
if (Equals(FindObjectOfType<Canvas>().tag, pauseCanvasTag))
pauseCanvas = FindObjectOfType<Canvas>();
if (Equals(anim, null))
anim = pauseCanvas.GetComponent<Animator>();
pausableInterfaces = pausable.GetComponents(typeof(IPausable));
quittableInterfaces = pausable.GetComponents(typeof(IQuittable));
pauseCanvas.enabled = false;
debugMode = PlayFabController.GetString("DebugMode");
if (Equals(debugMode, "true"))
{
Debug.Log("PauseManager.Start - Complete.");
}
}
void Update()
{
if (Input.GetKeyDown(PauseKey))
{
if (isPaused)
{
OnUnPause();
}
else {
OnPause();
}
}
pauseCanvas.enabled = isPaused;
anim.SetBool("IsPaused", isPaused);
}
public void OnQuit()
{
debugMode = PlayFabController.GetString("DebugMode");
if (Equals(debugMode, "true"))
Debug.Log("PauseManager.OnQuit");
foreach (var quittableComponent in quittableInterfaces)
{
IQuittable quittableInterface = (IQuittable)quittableComponent;
if (quittableInterface != null)
quittableInterface.OnQuit();
}
}
public void OnUnPause()
{
debugMode = PlayFabController.GetString("DebugMode");
if (Equals(debugMode, "true"))
Debug.Log("PauseManager.OnUnPause");
isPaused = false;
foreach (var pausableComponent in pausableInterfaces)
{
IPausable pausableInterface = (IPausable)pausableComponent;
if (pausableInterface != null)
pausableInterface.OnUnPause();
}
}
public void OnPause()
{
debugMode = PlayFabController.GetString("DebugMode");
if (Equals(debugMode, "true"))
Debug.Log("PauseManager.OnPause");
isPaused = true;
foreach (var pausableComponent in pausableInterfaces)
{
IPausable pausableInterface = (IPausable)pausableComponent;
if (pausableInterface != null)
pausableInterface.OnPause();
}
}
}
#region About
/**
* Company: PlayFab, InfoGamers, ZeredaGames
* Product: Player Login with Playfab
* Bundle Version: V1.0.0.2.0 //Build Version, Major Update, Minor Update, Revision, Patch
* PlayFabController.cs
* Created by: PlayFab/InfoGamer, Revision (Merge) by ZeredaGames
* Created on: (3/3/2019)-(3/7/2019)
*/
#endregion
#region Licencing
#endregion
#region using
#region Unity
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine.UI;
//using UnityEngine.SceneManagement;
#endregion
#region System
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
#endregion
#region PlayFab
using PlayFab;
using PlayFab.ClientModels;
using PlayFab.DataModels;
using PlayFab.Json;
using PlayFab.ProfilesModels;
using PlayFab.UI;
#endregion
#if FACEBOOK
using Facebook.Unity;
#endif
#if GOOGLEGAMES
using GooglePlayGames;
using GooglePlayGames.BasicApi;
#endif
using ZeredaGamesEngine.Core.GeneralScripts;
#endregion
#region Class's
#region Attributes
//[RequireComponent (typeof())]
//[System.Serializable]
#endregion
#region PlayFabController-Class
[RequireComponent(typeof(InternalSington))]
public class PlayFabController : MonoBehaviour
{
#region Control
#region Awake Calls
private void Awake()
{
SingtonInstance = GetComponent<InternalSington>();
SingtonInstance.AwakeSingleton();
OnCheckTitleID();
OnClearPlayerPrefs();
OnSubscribeEvents();
OnHideAllGUI();
if (EnableDevSetting) {
OnTestMode(TestMode);
if (TestMode)
{
DebugMode = TestMode;
}
else {
DebugMode = InternalSington.GetDebugMode;
}
}
SingtonInstance.DebugMode = DebugMode;
// Set the data we want at login from what we chose in our meta data.
_AuthService.InfoRequestParams = InfoRequestParams;
// Start the authentication process.
_AuthService.Authenticate();
//Set our remember me button to our remembered state.
RememberMe.isOn = _AuthService.RememberMe;
//Subscribe to our Remember Me toggle
RememberMe.onValueChanged.AddListener((toggle) =>
{
_AuthService.RememberMe = toggle;
});
if (ClearPlayerPrefs)
ClearPlayerPrefs = false;
if (UseGooglePlayLogin)
{
OnGooglePlayAwake();
}
else {
if (DebugMode)
Debug.Log("Dev Not Using GooglePlay Login.");
}
if (UseFacebookLogin)
{
OnFacebookAwake();
}
else {
if (DebugMode)
Debug.Log("Dev Not Using Facebook Login.");
}
}
private void OnSubscribeEvents()
{
// Subscribe to events that happen after we authenticate
PlayFabAuthService.OnDisplayAuthentication += OnDisplayAuthentication;
PlayFabAuthService.OnLoginSuccess += OnLoginSuccess;
PlayFabAuthService.OnPlayFabError += OnPlayFabError;
}
private void OnHideAllGUI()
{
// Hide all our panels until we know what UI to display
if (UseLoginOnly)
{
OnLoginSetup();
OnAutoLogin();
CheckIfLoginPanelExists(false);
CheckIfLoggedinPanelExists(false);
CheckIfRecoverySendPanelExists(false);
CheckIfRecoveryNewPassPanelExists(false);
CheckIfRegisterPanelExists(false);
CheckIfChangePassPanelExists(false);
CheckIfDevSettingsPanelExists(false);
CheckIfLeaderboadPanelExists(false);
if (DebugMode)
Debug.Log("Dev Using Login Only.");
}
else {
OnLoginSetup();
OnAutoLogin();
CheckIfLoginPanelExists(false);
CheckIfLoggedinPanelExists(false);
CheckIfChangePassPanelExists(false);
CheckIfDevSettingsPanelExists(false);
CheckIfLeaderboadPanelExists(false);
if (UseRegisterPanel)
{
OnRegisterSetup();
CheckIfRegisterPanelExists(false);
}
else {
if (DebugMode)
Debug.Log("Dev Not Using Registration.");
}
if (UseRecoveryPanel)
{
OnRecoverSetup();
CheckIfRecoverySendPanelExists(false);
CheckIfRecoveryNewPassPanelExists(false);
}
else {
if (DebugMode)
Debug.Log("Dev Not Using Recovery.");
}
if (UseTwoFactorAuthenitcationPanel)
{
CheckIfTwoFactorAuthenticationPanelExists(false);
}
else {
if (DebugMode)
Debug.Log("Dev Not Using Two Factor Authenitcation.");
}
}
}
private void OnCheckTitleID()
{
//Note: Setting title Id here can be skipped if you have set the value in Editor Extensions already.
if (string.IsNullOrEmpty(PlayFabSettings.TitleId))
{
PlayFabSettings.TitleId = string.Format("{0}", YourTitleIDForPlayfab);
}
if (Instance.DebugMode)
Debug.Log("PlayFabSettings.TitleId: " + PlayFabSettings.TitleId);
}
private void OnClearPlayerPrefs()
{
if (ClearPlayerPrefs)
{
_AuthService.UnlinkSilentAuth();
_AuthService.ClearRememberMe();
_AuthService.AuthType = Authtypes.None;
}
}
#endregion
#region Update Calls
private void Update()
{
OnPlayerLoginCheck();
if (!HasChangedPass)
{
ChangePassPanel.SetActive(true);
}
else {
ChangePassPanel.SetActive(false);
}
if (ChangeHeader)
{
StatusText.text = string.Format("Registering User {0} ... ", userName);
}
else {
StatusText.text = string.Format("Registering User {0} ... {1}", userName, "You should change your password.");
}
ShowPassword();
ShowPasswordRecovery();
ShowConfirmPasswordRecovery();
ShowPasswordNew();
ShowConfirmPasswordNew();
}
#endregion
#endregion
#region Dev Settings
[Header("Dev Settings:")]
public bool EnableDevSetting = true;
public bool DebugMode = true;
public static PlayFabController Instance;
public static InternalSington SingtonInstance;
// 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)
private string ClearSigninButtonTag = "ClearSigninButton";
private string ResetSampleButtonTag = "ResetSampleButton";
public string OpenDevSettingButtonTag = "OpenDevSettingButton";
public string DebugModeButtonTag = "DebugModeButton";
public string ResetPlayerPrefsButtonTag = "ResetPlayerPrefsButton";
private string ClearPurchasingDataButtonTag = "ClearPurchasingDataButton";
public string CloseDevSettingsButtonTag = "CloseDevSettingsButton";
public string DevSettingsPanelTag = "DevSettingsPanel";
/// <summary>
/// Set the amount of time before we auto load next level upon login.
/// </summary>
[Tooltip("Set the amount of time before we auto load next level upon login.")]
public float TimeToWait = 0.5f;
/// <summary>
/// Controlls Debug Logs, and a few update buttons.
/// </summary>
[Tooltip("Controlls Debug Logs, and a few update buttons.")]
public bool TestMode = true;
/// <summary>
/// If True: Player has to input all data again on a failed attempt(Failed attempt being the password and the confirm passwords do not match), otherwise, it only clear's the passwords on the login panel.
/// </summary>
[Tooltip("If True: Player has to input all data again on a failed attempt(Failed attempt being the password and the confirm passwords do not match), otherwise, it only clear's the passwords on the login panel.")]
public bool UseClearAllData;
/// <summary>
/// Debug Flag to simulate a reset.
/// </summary>
[Tooltip("Debug Flag to simulate a reset.")]
public bool ClearPlayerPrefs;
/// <summary>
/// Flag for using login Only Panel.
/// </summary>
[Tooltip("Flag for using login Only Panel.")]
public bool UseLoginOnly = true;
/// <summary>
/// Flag for using RegisterPanel.
/// </summary>
[Tooltip("Flag for using RegisterPanel.")]
public bool UseRegisterPanel = true;
/// <summary>
/// Flag for using Recovery Panel.
/// </summary>
[Tooltip("Flag for using Recovery Panel.")]
public bool UseRecoveryPanel = true;
/// <summary>
/// Flag for using TwoFactorAuthenitcation Login.
/// </summary>
[Tooltip("Flag for using TwoFactorAuthenitcation Login.")]
public bool UseTwoFactorAuthenitcationPanel = true;
/// <summary>
/// Flag for using Facebook Login.
/// </summary>
[Tooltip("Flag for using Facebook Login.")]
public bool UseFacebookLogin = true;
/// <summary>
/// Flag for using GooglePlay Login.
/// </summary>
[Tooltip("Flag for using GooglePlay Login.")]
public bool UseGooglePlayLogin = true;
/// <summary>
/// Please change this value to your own Title ID from PlayFab Game Manager.
/// </summary>
[Tooltip("Please change this value to your own Title ID from PlayFab Game Manager.")]
public string YourTitleIDForPlayfab;
/// <summary>
/// Settings for what data to get from playfab on login.
/// </summary>
[Tooltip("Settings for what data to get from playfab on login.")]
public GetPlayerCombinedInfoRequestParams InfoRequestParams;
/// <summary>
/// Reference to our Authentication service.
/// </summary>
[Tooltip("Reference to our Authentication service.")]
private PlayFabAuthService _AuthService = PlayFabAuthService.Instance;
/// <summary>
/// The Panel with 'Dev Setting Inputs' on it.
/// </summary>
private GameObject DevSettingsPanel;
/// <summary>
/// Used to clear all InputFields.
/// </summary>
private Button ClearSigninButton;
/// <summary>
/// Clears the Authentication services.
/// </summary>
private Button ResetSampleButton;
/// <summary>
/// Opens the DevSettings Panel.
/// </summary>
private Button OpenDevSettingButton;
/// <summary>
/// Toggles Debug Calls.
/// </summary>
private Button DebugModeButton;
/// <summary>
/// Clears the PlayerPrefs for the Player.
/// </summary>
private Button ResetPlayerPrefsButton;
/// <summary>
/// Delete All Purchassing Data In Unity Editor.
/// </summary>
private Button ClearPurchasingDataButton;
/// <summary>
/// Closes the Panel with 'Dev Setting Inputs' on it.
/// </summary>
private Button CloseDevSettingsButton;
private static string myID = "";
private void OnTestMode(bool testMode)
{
if (TestMode)
{
DevSettingsPanel = GameObject.FindGameObjectWithTag(DevSettingsPanelTag);
ResetSampleButton = GameObject.FindGameObjectWithTag(ResetSampleButtonTag).GetComponent<Button>();
ClearSigninButton = GameObject.FindGameObjectWithTag(ClearSigninButtonTag).GetComponent<Button>();
OpenDevSettingButton = GameObject.FindGameObjectWithTag(OpenDevSettingButtonTag).GetComponent<Button>();
CloseDevSettingsButton = GameObject.FindGameObjectWithTag(CloseDevSettingsButtonTag).GetComponent<Button>();
DebugModeButton = GameObject.FindGameObjectWithTag(DebugModeButtonTag).GetComponent<Button>();
ResetPlayerPrefsButton = GameObject.FindGameObjectWithTag(ResetPlayerPrefsButtonTag).GetComponent<Button>();
ClearPurchasingDataButton = GameObject.FindGameObjectWithTag(ClearPurchasingDataButtonTag).GetComponent<Button>();
ResetSampleButton.onClick.AddListener(OnResetSampleButtonClicked);
ClearSigninButton.onClick.AddListener(OnClearSigninButtonClicked);
OpenDevSettingButton.onClick.AddListener(OnActivateDevSettingWindowClick);
CloseDevSettingsButton.onClick.AddListener(OnDeactivateDevSettingWindowClick);
DebugModeButton.onClick.AddListener(ToggleDebugMode);
ResetPlayerPrefsButton.onClick.AddListener(DeleteAll);
ClearPurchasingDataButton.onClick.AddListener(OnClearUnityPurchasingPath);
}
}
private void ToggleDebugMode()
{
Instance.DebugMode = !Instance.DebugMode;
if (Instance.DebugMode)
{
InternalSington.OnSetDebugMode = Instance.DebugMode;
}
}
/// <summary>
/// Activates the game object.
/// </summary>
/// <param name="gameObject">Game object.</param>
public void ActivateGameObject(GameObject obj)
{
obj.SetActive(true);
if (Instance.DebugMode)
Debug.Log("ActivateGameObject: " + obj.name);
}
/// <summary>
/// Deactivates the game object.
/// </summary>
/// <param name="gameObject">Game object.</param>
public void DeactivateGameObject(GameObject obj)
{
obj.SetActive(false);
if (Instance.DebugMode)
Debug.Log("DeactivateGameObject: " + obj.name);
}
private void OnDisplayWarningWindow(string message)
{
GameObject OnDisplayWarningWindow = GameObject.FindGameObjectWithTag("Warning Window");
if (Equals(OnDisplayWarningWindow, null))
{
if (Instance.DebugMode)
Debug.Log("No Warning Panel In scene");
}
else
{
OnDisplayWarningWindow.SetActive(true);
Text warningText = GameObject.FindGameObjectWithTag("WarningText").GetComponent<Text>();
warningText.text = message;
}
}
private void OnResetSampleButtonClicked()
{
if (!RememberMe.isOn)
{
PlayFabClientAPI.ForgetAllCredentials();
_AuthService.Email = string.Empty;
_AuthService.Password = string.Empty;
_AuthService.AuthTicket = string.Empty;
_AuthService.Authenticate();
StatusText.text = "Signin info cleared";
}
}
private void OnClearSigninButtonClicked()
{
_AuthService.ClearRememberMe();
RememberMe.isOn = false;
StatusText.text = "Signin info cleared";
}
private void OnActivateDevSettingWindowClick() {
DevSettingsPanel.SetActive(true);
}
private void OnDeactivateDevSettingWindowClick()
{
DevSettingsPanel.SetActive(false);
}
private void Toggle2FA()
{
SetTwoFactorAuthenticationEnabled.isOn = !SetTwoFactorAuthenticationEnabled.isOn;
TwoFactorEnabledImage.gameObject.SetActive(SetTwoFactorAuthenticationEnabled.isOn);
TwoFactorAuthenticationEnabled = SetTwoFactorAuthenticationEnabled.isOn;
if (TwoFactorAuthenticationEnabled)
{
SetInt("Two Factor Authentication Enabled", 1);
}
else {
SetInt("Two Factor Authentication Enabled", 0);
}
}
private void Show2FAPanel()
{
int checkTwoFactorAuthentication = GetInt("Two Factor Authentication Enabled", 1);
if (Equals(checkTwoFactorAuthentication, 1))
{
if (SetTwoFactorAuthenticationEnabled.isOn)
{
TwoFactorAuthenticationEnabled = true;
TwoFactorAuthenticationPanel.SetActive(true);
}
else {
TwoFactorAuthenticationEnabled = false;
TwoFactorAuthenticationPanel.SetActive(false);
}
}
else {
TwoFactorAuthenticationEnabled = false;
SetTwoFactorAuthenticationEnabled.isOn = false;
}
}
private void CheckIfLoginPanelExists(bool enable)
{
if (!Equals(LoginPanel, null))
LoginPanel.SetActive(enable);
}
private void CheckIfTwoFactorAuthenticationPanelExists(bool enable)
{
if (!Equals(LoginPanel, null))
TwoFactorAuthenticationPanel.SetActive(enable);
}
private void CheckIfLoggedinPanelExists(bool enable)
{
if (!Equals(LoggedinPanel, null))
LoggedinPanel.SetActive(enable);
}
private void CheckIfRecoverySendPanelExists(bool enable)
{
if (!Equals(RecoverySendPanel, null))
RecoverySendPanel.SetActive(enable);
}
private void CheckIfRecoveryNewPassPanelExists(bool enable)
{
if (!Equals(RecoveryNewPassPanel, null))
RecoveryNewPassPanel.SetActive(enable);
}
private void CheckIfRegisterPanelExists(bool enable)
{
if (!Equals(RegisterPanel, null))
RegisterPanel.SetActive(enable);
}
private void CheckIfChangePassPanelExists(bool enable)
{
if (!Equals(ChangePassPanel, null))
ChangePassPanel.SetActive(enable);
}
private void CheckIfDevSettingsPanelExists(bool enable)
{
if (!Equals(DevSettingsPanel, null))
DevSettingsPanel.SetActive(enable);
}
private void CheckIfLeaderboadPanelExists(bool enable) {
if (!Equals(DevSettingsPanel, null))
LeaderboardPanel.SetActive(enable);
}
#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 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()
{
OpenLeaderboardButton = GameObject.FindGameObjectWithTag(OpenLeaderboardButtonTag).GetComponent<Button>();
CloseLeaderboardButton = GameObject.FindGameObjectWithTag(CloseLeaderboardButtonTag).GetComponent<Button>();
var requestLeaderboard = new GetLeaderboardRequest { StartPosition = 0, StatisticName = "PlayerHighScore", MaxResultsCount = 20 };
PlayFabClientAPI.GetLeaderboard(requestLeaderboard, OnGetLeadboard, OnErrorLeaderboard);
}
private void OnGetLeadboard(GetLeaderboardResult result)
{
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()
{
CheckIfLeaderboadPanelExists(false);
for (int i = listingContainer.childCount - 1; i >= 0; i--)
{
Destroy(listingContainer.GetChild(i).gameObject);
}
}
private void OnErrorLeaderboard(PlayFabError error)
{
if (Instance.DebugMode)
Debug.LogError(error.GenerateErrorReport());
}
#endregion
#region Login
// 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("Return User:")]
private string UserNameTag = "UserNameInputField";
private string PasswordTag = "PasswordInputField";
private string ShowPasswordToggleTag = "ShowPasswordToggle";
private string RememberMeTag = "RememberMeToggle";
private string LoginButtonTag = "LoginButton";
private string MakeNewButtonTag = "MakeNewButton";
private string ForgotPasswordButtonTag = "ForgotPasswordButton";
private string StatusTextTag = "StatusText";
private string UserNameDisplayTag = "UserNameDisplay";
private string ProgressBarTag = "ProgressBar";
private string LoginPanelTag = "LoginPanel";
private string LoggedinPanelTag = "LoggedinPanel";
/// <summary>
/// Main Login Panel
/// </summary>
private GameObject LoginPanel;
/// <summary>
/// Logged In Panel, Place notes on here.
/// </summary>
private GameObject LoggedinPanel;
private static string password = "";
private static string confirmPassword = "";
private static string email = "";
private static string userName = "";
private bool isPlayerLoggedIn;
private bool checkUserPass = false;
private bool CheckUserPassword
{
get
{
if (Equals(password, confirmPassword))
{
if (DebugMode)
Debug.Log("Passwords Match");
return true;
}
else {
if (UseClearAllData)
{
OnCancelRegisterButtonClicked();
if (DebugMode)
Debug.LogError("All data has been cleared.");
}
else {
password = "";
confirmPassword = "";
}
if (DebugMode)
Debug.LogErrorFormat("Passwords Don't Match, make sure both the password and confirm passwords match. Result: {0}:{1}", password, confirmPassword);
return false;
}
}
}
private bool fired = false;
private const string IDKEY = "PlayerDeviceID";
private const string PlayerPassKey = "PlayerPass";
/// <summary>
/// Input Field On your Main Login.
/// </summary>
private InputField UserName;
/// <summary>
/// Input Field On your Main Login.
/// </summary>
private InputField Password;
/// <summary>
/// Toggle On your Main Login.
/// </summary>
private Toggle ShowPasswordToggle;
/// <summary>
/// Toggle On your Main Login.
/// </summary>
private Toggle RememberMe;
/// <summary>
/// Button On your Main Login.
/// </summary>
private Button LoginButton;
/// <summary>
/// Button On your Main Login.
/// </summary>
private Button MakeNewButton;
/// <summary>
/// Button On your Main Login.
/// </summary>
private Button ForgotPasswordButton;
/// <summary>
/// Text On your Main Login.
/// </summary>
private Text StatusText;
/// <summary>
/// Text On your Main Login.
/// </summary>
private Text UserNameDisplay;
/// <summary>
/// ProgressBarView On your Main Login.
/// </summary>
private ProgressBarView ProgressBar;
public static string ReturnSystemID
{
get
{
string message = SystemInfo.deviceUniqueIdentifier;
return GetString(IDKEY, message);
}
private set
{
string message = SystemInfo.deviceUniqueIdentifier;
SetString(IDKEY, message);
message = value;
}
}
private void OnLoginSetup()
{
LoginPanel = GameObject.FindGameObjectWithTag(LoginPanelTag);
LoggedinPanel = GameObject.FindGameObjectWithTag(LoggedinPanelTag);
UserName = GameObject.FindGameObjectWithTag(UserNameTag).GetComponent<InputField>();
Password = GameObject.FindGameObjectWithTag(PasswordTag).GetComponent<InputField>();
ShowPasswordToggle = GameObject.FindGameObjectWithTag(ShowPasswordToggleTag).GetComponent<Toggle>();
RememberMe = GameObject.FindGameObjectWithTag(RememberMeTag).GetComponent<Toggle>();
LoginButton = GameObject.FindGameObjectWithTag(LoginButtonTag).GetComponent<Button>();
MakeNewButton = GameObject.FindGameObjectWithTag(MakeNewButtonTag).GetComponent<Button>();
ForgotPasswordButton = GameObject.FindGameObjectWithTag(ForgotPasswordButtonTag).GetComponent<Button>();
StatusText = GameObject.FindGameObjectWithTag(StatusTextTag).GetComponent<Text>();
UserNameDisplay = GameObject.FindGameObjectWithTag(UserNameDisplayTag).GetComponent<Text>();
ProgressBar = GameObject.FindGameObjectWithTag(ProgressBarTag).GetComponent<ProgressBarView>();
LoginButton.onClick.AddListener(OnLoginClicked);
MakeNewButton.onClick.AddListener(OnOpenRegistrationClicked);
ForgotPasswordButton.onClick.AddListener(OnOpenRecoveryClicked);
}
/// <summary>
/// Login Button means they've selected to submit a username (email) / password combo
/// Note: in this flow if no account is found, it will ask them to register.
/// </summary>
private void OnLoginClicked()
{
ProgressBar.UpdateLabel(string.Format("Logging In As {0} ...", UserName.text));
ProgressBar.UpdateProgress(0f);
ProgressBar.AnimateProgress(0, 1, () => {
//second loop
ProgressBar.UpdateProgress(0f);
ProgressBar.AnimateProgress(0, 1, () => {
ProgressBar.UpdateLabel(string.Empty);
ProgressBar.UpdateProgress(0f);
});
});
_AuthService.Username = UserName.text;
_AuthService.Password = Password.text;
_AuthService.Authenticate(Authtypes.UsernameAndPassword);
GetUsername(UserName.text);
GetUserPassword(Password.text);
if (HasKey("EMAIL"))
{
GetUserEmail(GetString("EMAIL"));
GetUserPasswordConfirm(GetString("CONFIRMPASSWORD"));
_AuthService.Email = GetString("EMAIL");
}
GetStats();
GetPlayerData();
checkUserPass = CheckUserPassword;
if (checkUserPass)
{
var request = new LoginWithEmailAddressRequest { TitleId = userName, Email = email, Password = password };
PlayFabClientAPI.LoginWithEmailAddress(request, OnLoginSuccess, OnPlayFabError);
if (isPlayerLoggedIn)
{
PlayFabClientAPI.UpdateUserTitleDisplayName(new UpdateUserTitleDisplayNameRequest { DisplayName = UserName.text }, OnDisplayName, OnPlayFabError);
InitializeNewEncryptionKey(userName, password, email);//Each Player Get's their own encryption for PPs
}
}
else {
if (Instance.DebugMode)
Debug.LogError("Passwords do not match. Nothing happend. This message is In Your 'public void OnLoginClickButton()', but it failed in the 'CheckUserPassword' bool property.");
}
LoginPanel.SetActive(false);
LoggedinPanel.SetActive(true);
StopPasswordTimer();
StatusText.text = string.Format("Logging In As {0} ...", userName);
Show2FAPanel();
if (TwoFactorAuthenticationEnabled)
{
TwoFactorAuthenticationPanel.SetActive(true);
OnDisplayWarningWindow("Two Factor Autentication Enabled.");
}
}
#region OtherLoginTypes
void OtherLoginTypes()
{
#if UNITY_EDITOR
if (Instance.DebugMode)
Debug.Log("Unity Editor");
#endif
#if UNITY_ANDROID
OnAndroid();
if (Instance.DebugMode)
Debug.Log("Android");
#endif
#if UNITY_IOS
OniOS();
if (Instance.DebugMode)
Debug.Log("Iphone");
#endif
#if UNITY_STANDALONE_OSX
OnOSX();
if (Instance.DebugMode)
Debug.Log("Stand Alone OSX");
#endif
#if UNITY_STANDALONE_WIN
OnPC();
if (Instance.DebugMode)
Debug.Log("Stand Alone Windows");
#endif
#if UNITY_STANDALONE
OnWebGL();
if (Instance.DebugMode)
Debug.Log("Stand Alone");
#endif
#if UNITY_WII
OnWii();
if (Instance.DebugMode)
Debug.Log("Wii");
#endif
#if UNITY_IPHONE
OnIPhone();
if (Instance.DebugMode)
Debug.Log("iPhone");
#endif
#if UNITY_XBOXONE
OnXbox();
if (Instance.DebugMode)
Debug.Log("Xbox One");
#endif
#if UNITY_FACEBOOK
OnFacebook();
if (Instance.DebugMode)
Debug.Log("Facebook");
#endif
}
#if (!UNITY_ANDROID || (!UNITY_IPHONE))
void OnOSX()
{
if (HasKey("EMAIL"))
{
if (Instance.DebugMode)
Debug.Log("Mac OSX:");
var request = new LoginWithGameCenterRequest { PlayerId = userName, CreateAccount = true };
PlayFabClientAPI.LoginWithGameCenter(request, OnLoginSuccess, OnPlayFabError);
}
else {
OnDisplayWarningWindow("[WARNING] No 'Email-Key' on this Machine.");
}
}
void OnPC()
{
if (HasKey("EMAIL"))
{
if (Instance.DebugMode)
Debug.Log("Windows:");
var request = new LoginWithEmailAddressRequest { Email = email, Password = Password.text };
PlayFabClientAPI.LoginWithEmailAddress(request, OnLoginSuccess, OnPlayFabError);
}
else {
OnDisplayWarningWindow("[WARNING] No 'Email-Key' on this PC.");
}
}
void OnWebGL()
{
if (HasKey("EMAIL"))
{
if (Instance.DebugMode)
Debug.Log("WebGL:");
var request = new LoginWithEmailAddressRequest { Email = email, Password = Password.text };
PlayFabClientAPI.LoginWithEmailAddress(request, OnLoginSuccess, OnPlayFabError);
}
else {
OnDisplayWarningWindow("[WARNING] No 'Email-Key' on this Server.");
}
}
void OnSwitch()
{
if (HasKey("EMAIL"))
{
if (Instance.DebugMode)
Debug.Log("Switch:");
var request = new LoginWithNintendoSwitchDeviceIdRequest { NintendoSwitchDeviceId = ReturnSystemID, CreateAccount = true };
PlayFabClientAPI.LoginWithNintendoSwitchDeviceId(request, OnLoginSuccess, OnPlayFabError);
}
else {
OnDisplayWarningWindow("[WARNING] No 'Email-Key' on this device.");
}
}
void OnTwitch()
{
if (HasKey("EMAIL"))
{
if (Instance.DebugMode)
Debug.Log("Twitch:");
var request = new LoginWithTwitchRequest { AccessToken = ReturnSystemID, CreateAccount = true };
PlayFabClientAPI.LoginWithTwitch(request, OnLoginSuccess, OnPlayFabError);
}
else {
OnDisplayWarningWindow("[WARNING] No 'Email-Key' on this Server.");
}
}
void OnXbox()
{
if (HasKey("EMAIL"))
{
if (Instance.DebugMode)
Debug.Log("Xbox One:");
var request = new LoginWithXboxRequest { XboxToken = ReturnSystemID, CreateAccount = true };
PlayFabClientAPI.LoginWithXbox(request, OnLoginSuccess, OnPlayFabError);
}
else {
OnDisplayWarningWindow("[WARNING] No 'Email-Key' on this Console.");
}
}
#endif
#if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS))
void OnAndroid()
{
if (HasKey("EMAIL"))
{
if (Instance.DebugMode)
Debug.Log("Android:");
var requestAndroid = new LoginWithAndroidDeviceIDRequest { AndroidDeviceId = ReturnSystemID, CreateAccount = true };
PlayFabClientAPI.LoginWithAndroidDeviceID(requestAndroid, OnLoginSuccess, OnPlayFabError);
}
else {
OnDisplayWarningWindow("No Email Key on ");
}
}
void OniOS()
{
if (HasKey("EMAIL"))
{
if (Instance.DebugMode)
Debug.Log("Apple iOS:");
var requestIOS = new LoginWithIOSDeviceIDRequest { DeviceId = ReturnSystemID, CreateAccount = true };
PlayFabClientAPI.LoginWithIOSDeviceID(requestIOS, OnLoginSuccess, OnPlayFabError);
}
else {
OnDisplayWarningWindow("[WARNING] No 'Email-Key' on this device.");
}
}
void OnFacebook()
{
if (HasKey("EMAIL"))
{
if (Instance.DebugMode)
Debug.Log("Facebook:");
var request = new LoginWithFacebookRequest { AccessToken = userName, CreateAccount = true };
PlayFabClientAPI.LoginWithFacebook(request, OnLoginSuccess, OnPlayFabError);
}
else {
OnDisplayWarningWindow("[WARNING] No 'Email-Key' on this Server.");
}
}
void OnIPhone()
{
if (HasKey("EMAIL"))
{
if (Instance.DebugMode)
Debug.Log("iPhone:");
var requestIOS = new LoginWithIOSDeviceIDRequest { DeviceId = ReturnSystemID, CreateAccount = true };
PlayFabClientAPI.LoginWithIOSDeviceID(requestIOS, OnLoginSuccess, OnPlayFabError);
}
else {
OnDisplayWarningWindow("[WARNING] No 'Email-Key' on this device.");
}
}
private void OnDestroy()
{
LoginButton.onClick.RemoveListener(OnLoginButtonClicked);
}
private void OnSignInGoogleButtonClicked()
{
Social.localUser.Authenticate((bool success) => {
StatusText.text = "Google Signed In";
var serverAuthCode = PlayGamesPlatform.Instance.GetServerAuthCode();
Debug.Log("Server Auth Code: " + serverAuthCode);
PlayFabClientAPI.LoginWithGoogleAccount(new LoginWithGoogleAccountRequest()
{
TitleId = PlayFabSettings.TitleId,
ServerAuthCode = serverAuthCode,
CreateAccount = true
}, (result) => {
GoogleStatusText.text = "Signed In as " + result.PlayFabId;
}, OnPlayFabError);
});
}
#endif
#endregion
/// <summary>
/// Choose to display the Auth UI or any other action.
/// </summary>
private void OnDisplayAuthentication()
{
#if FACEBOOK
if (FB.IsInitialized)
{
if(DebugMode)
Debug.LogFormat("FB is Init: AccessToken:{0} IsLoggedIn:{1}",AccessToken.CurrentAccessToken.TokenString, FB.IsLoggedIn);
if (AccessToken.CurrentAccessToken == null || !FB.IsLoggedIn)
{
LoginPanel.SetActive(false);
LoggedInPanel.SetActive(true);
}
}
else
{
LoginPanel.SetActive(true);
LoggedInPanel.SetActive(false);
if(DebugMode)
Debug.Log("FB Not Initialized.");
}
#else
//Here we have choses what to do when AuthType is None.
LoginPanel.SetActive(true);
LoggedinPanel.SetActive(false);
StatusText.text = "";
#endif
/*
* Optionally we could Not do the above and force login silently
*
* _AuthService.Authenticate(Authtypes.Silent);
*
* This example, would auto log them in by device ID and they would
* never see any UI for Authentication.
*
*/
}
private void OnPlayerLoginCheck()
{
if (isPlayerLoggedIn && !fired)
{
ClickToLoadAsync ctla = FindObjectOfType<ClickToLoadAsync>();
ctla.WaitTime = TimeToWait;
ctla.LoadNextSceneWithAsync();
fired = true;
_AuthService.RememberMe = RememberMe.isOn;
if (fired)
{
if (DebugMode)
Debug.LogFormat("Fired: {0}. Time Set to {1}.", fired, ctla.WaitTime);
}
}
}
private void OnAutoLogin()
{
//var request = new LoginWithCustomIDRequest { CustomId = "GettingStartedGuide", CreateAccount = true };
//PlayFabClientAPI.LoginWithCustomID(request, OnLoginSuccess, OnFailureToLogin);
if (PlayFabController.HasKey("EMAIL"))
{
if (Instance.DebugMode)
Debug.Log("Auto-Login");
email = GetString("EMAIL");
password = GetString("PASSWORD");
var request = new LoginWithEmailAddressRequest { Email = email, Password = password };
PlayFabClientAPI.LoginWithEmailAddress(request, OnLoginSuccess, OnPlayFabError);
}
else
{
OtherLoginTypes();
}
}
private void GetUserEmail(string emailIn)
{
email = emailIn;
SetString("EMAIL", email);
}
private void GetUserPassword(string passwordIn)
{
password = passwordIn;
SetString("PASSWORD", password);
}
private void GetUserPasswordConfirm(string passwordIn)
{
confirmPassword = passwordIn;
SetString("CONFIRMPASSWORD", confirmPassword);
}
private void GetUsername(string usernameIn)
{
userName = usernameIn;
UserNameDisplay.text = userName;
SetString("USERNAME", userName);
}
private void ShowPassword()
{
if (ShowPasswordToggle.isOn)
{
Password.contentType = InputField.ContentType.Alphanumeric;
}
else {
Password.contentType = InputField.ContentType.Password;
}
}
#endregion
#region Register
// 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("Register New Account:")]
private string RegisterPanelTag = "RegisterPanel";
private string _UserNameTag = "UserName2InputField";
private string _EmailTag = "Email2InputField";
private string _PasswordTag = "Password2AInputField";
private string _ConfirmPasswordTag = "ConfirmPassword2BInputField";
private string LoginWithFacebookButtonTag = "LoginWithFacebookButton";
private string LoginWithGoogleButtonTag = "LoginWithGoogleButton";
public string LoginWithTwitchAccountButtonTag = "LoginWithTwitchAccountButton";
private string PlayAsGuestButtonTag = "PlayAsGuestButton";
private string RegisterButtonTag = "RegisterButton";
private string CancelRegisterButtonTag = "CancelRegisterButton";
public string EnableTwoFactorAuthButtonTag = "EnableTwoFactorAuthButton";
public string ShowNewPlayerPassTextToggleTag = "ShowNewPlayerPassTextToggle";
public string ShowNewPlayerConfirmPassTextToggleTag = "ShowNewPlayerConfirmPassTextToggle";
public string SetTwoFactorAuthenticationEnabledTag = "SetTwoFactorAuthenticationEnabled";
public string TwoFactorAuthenticationPanelTag = "TwoFactorAuthenticationPanel";
public string TwoFactorEnabledImageName = "TwoFactorEnabledImage";
/// <summary>
/// Input Field On your Register Login.
/// </summary>
private InputField _UserName;
/// <summary>
/// Input Field On your Register Login.
/// </summary>
private InputField _Email;
/// <summary>
/// Input Field On your Register Login.
/// </summary>
private InputField _Password;
/// <summary>
/// Input Field On your Register Login.
/// </summary>
private InputField _ConfirmPassword;
/// <summary>
/// Button On your Register Login.
/// </summary>
private Button LoginWithFacebook;
/// <summary>
/// Button On your Register Login.
/// </summary>
private Button LoginWithGoogle;
/// <summary>
/// Button On your Register Login.
/// </summary>
private Button LoginWithTwitchAccount;
/// <summary>
/// Button On your Register Login.
/// </summary>
private Button PlayAsGuestButton;
/// <summary>
/// Button On your Register Login.
/// </summary>
private Button RegisterButton;
/// <summary>
/// Button On your Register Login.
/// </summary>
private Button CancelRegisterButton;
/// <summary>
/// Button On your Register Login.
/// </summary>
private Button EnableTwoFactorAuthButton;
/// <summary>
/// Toggle On your Register Login.
/// </summary>
private Toggle ShowNewPlayerPassTextToggle;
/// <summary>
/// Toggle On your Register Login.
/// </summary>
private Toggle ShowNewPlayerConfirmPassTextToggle;
/// <summary>
/// Toggle On your Register Login.
/// </summary>
private Toggle SetTwoFactorAuthenticationEnabled;
/// <summary>
/// Create New Player Panel
/// </summary>
private GameObject RegisterPanel;
/// <summary>
/// In Case we want to use 2 factor Authentication.
/// </summary>
private GameObject TwoFactorAuthenticationPanel;
/// <summary>
/// An Image that can indicate to the player that they have in face enabled the two Factor Authentication.
/// </summary>
private Image TwoFactorEnabledImage;
private bool TwoFactorAuthenticationEnabled;
private void OnRegisterSetup()
{
RegisterPanel = GameObject.FindGameObjectWithTag(RegisterPanelTag);
TwoFactorAuthenticationPanel = GameObject.FindGameObjectWithTag(TwoFactorAuthenticationPanelTag);
TwoFactorEnabledImage = Resources.Load<Image>(TwoFactorEnabledImageName);
_UserName = GameObject.FindGameObjectWithTag(_UserNameTag).GetComponent<InputField>();
_Email = GameObject.FindGameObjectWithTag(_EmailTag).GetComponent<InputField>();
_Password = GameObject.FindGameObjectWithTag(_PasswordTag).GetComponent<InputField>();
_ConfirmPassword = GameObject.FindGameObjectWithTag(_ConfirmPasswordTag).GetComponent<InputField>();
LoginWithFacebook = GameObject.FindGameObjectWithTag(LoginWithFacebookButtonTag).GetComponent<Button>();
LoginWithGoogle = GameObject.FindGameObjectWithTag(LoginWithGoogleButtonTag).GetComponent<Button>();
LoginWithTwitchAccount = GameObject.FindGameObjectWithTag(LoginWithTwitchAccountButtonTag).GetComponent<Button>();
PlayAsGuestButton = GameObject.FindGameObjectWithTag(PlayAsGuestButtonTag).GetComponent<Button>();
RegisterButton = GameObject.FindGameObjectWithTag(RegisterButtonTag).GetComponent<Button>();
CancelRegisterButton = GameObject.FindGameObjectWithTag(CancelRegisterButtonTag).GetComponent<Button>();
EnableTwoFactorAuthButton = GameObject.FindGameObjectWithTag(EnableTwoFactorAuthButtonTag).GetComponent<Button>();
ShowNewPlayerPassTextToggle = GameObject.FindGameObjectWithTag(ShowNewPlayerPassTextToggleTag).GetComponent<Toggle>();
ShowNewPlayerConfirmPassTextToggle = GameObject.FindGameObjectWithTag(ShowNewPlayerConfirmPassTextToggleTag).GetComponent<Toggle>();
SetTwoFactorAuthenticationEnabled = GameObject.FindGameObjectWithTag(SetTwoFactorAuthenticationEnabledTag).GetComponent<Toggle>();
PlayAsGuestButton.onClick.AddListener(OnPlayAsGuestClicked);
RegisterButton.onClick.AddListener(OnRegisterButtonClicked);
CancelRegisterButton.onClick.AddListener(OnCancelRegisterButtonClicked);
LoginWithFacebook.onClick.AddListener(OnLoginWithFacebookClicked);
LoginWithGoogle.onClick.AddListener(OnLoginWithGoogleClicked);
LoginWithTwitchAccount.onClick.AddListener(OnLoginWithTwitchClicked);
EnableTwoFactorAuthButton.onClick.AddListener(Toggle2FA);
}
private void ShowPasswordNew()
{
if (ShowNewPlayerPassTextToggle.isOn)
{
_Password.contentType = InputField.ContentType.Alphanumeric;
}
else {
_Password.contentType = InputField.ContentType.Password;
}
}
private void ShowConfirmPasswordNew()
{
if (ShowNewPlayerConfirmPassTextToggle.isOn)
{
_ConfirmPassword.contentType = InputField.ContentType.Alphanumeric;
}
else {
_ConfirmPassword.contentType = InputField.ContentType.Password;
}
}
private void OnOpenRegistrationClicked() {
RegisterPanel.SetActive(true);
}
/// <summary>
/// Play As a guest, which means they are going to silently authenticate
/// by device ID or Custom ID
/// </summary>
private void OnPlayAsGuestClicked()
{
StatusText.text = "Logging In As Guest ...";
ProgressBar.UpdateLabel("Logging In As Guest ...");
ProgressBar.UpdateProgress(0f);
ProgressBar.AnimateProgress(0, 1, () => {
ProgressBar.UpdateLabel(string.Empty);
ProgressBar.UpdateProgress(0f);
});
_AuthService.Authenticate(Authtypes.Silent);
}
/// <summary>
/// No account was found, and they have selected to register a username (email) / password combo.
/// </summary>
private void OnRegisterButtonClicked()
{
if (Password.text != _ConfirmPassword.text)
{
StatusText.text = "Passwords do not Match.";
return;
}
ProgressBar.UpdateLabel(string.Format("Registering User {0} ...", UserName.text));
ProgressBar.UpdateProgress(0f);
ProgressBar.AnimateProgress(0, 1, () => {
//second loop
ProgressBar.UpdateProgress(0f);
ProgressBar.AnimateProgress(0, 1, () => {
ProgressBar.UpdateLabel(string.Empty);
ProgressBar.UpdateProgress(0f);
});
});
_AuthService.Username = _UserName.text;
_AuthService.Email = _Email.text;
_AuthService.Password = _Password.text;
_AuthService.Authenticate(Authtypes.RegisterPlayFabAccount);
GetUsername(_UserName.text);
GetUserPassword(_Password.text);
GetUserEmail(_Email.text);
GetUserPasswordConfirm(_ConfirmPassword.text);
GetStats();
GetPlayerData();
checkUserPass = CheckUserPassword;
if (checkUserPass)
{
var request = new LoginWithCustomIDRequest()
{
TitleId = PlayFabSettings.TitleId,
CustomId = SystemInfo.deviceUniqueIdentifier,
CreateAccount = true
};
PlayFabClientAPI.LoginWithCustomID(request, OnLoginSuccess, OnPlayFabError);
if (isPlayerLoggedIn)
{
PlayFabClientAPI.UpdateUserTitleDisplayName(new UpdateUserTitleDisplayNameRequest { DisplayName = userName }, OnDisplayName, OnPlayFabError);
InitializeNewEncryptionKey(userName, password, email);//Each Player Get's their own encryption for PPs
if (DebugMode)
Debug.LogFormat("Is Player Logged in: {0}", isPlayerLoggedIn);
}
}
else {
if (Instance.DebugMode)
Debug.LogError("Passwords do not match. Nothing happend. This message is In Your 'public void OnLoginClickButton()', but it failed in the 'CheckUserPassword' bool property.");
}
Show2FAPanel();
CheckIfLoginPanelExists(false);
CheckIfLoggedinPanelExists(true);
CheckIfRecoverySendPanelExists(false);
CheckIfRecoveryNewPassPanelExists(false);
CheckIfRegisterPanelExists(false);
CheckIfChangePassPanelExists(true);
CheckIfDevSettingsPanelExists(false);
StatusText.text = string.Format("Registering User {0} ...", userName);
}
/// <summary>
/// They have opted to cancel the Registration process.
/// Possibly they typed the email address incorrectly.
/// </summary>
private void OnCancelRegisterButtonClicked()
{
// Reset all forms
_UserName.text = string.Empty;
UserName.text = string.Empty;
userName = string.Empty;
_Email.text = string.Empty;
__Email.text = string.Empty;
email = string.Empty;
_Password.text = string.Empty;
Password.text = string.Empty;
password = string.Empty;
_ConfirmPassword.text = string.Empty;
__ConfirmPassword.text = string.Empty;
confirmPassword = string.Empty;
// Show panels
CheckIfLoginPanelExists(true);
CheckIfLoggedinPanelExists(false);
CheckIfRecoverySendPanelExists(false);
CheckIfRecoveryNewPassPanelExists(false);
CheckIfRegisterPanelExists(false);
CheckIfChangePassPanelExists(false);
CheckIfDevSettingsPanelExists(false);
}
#endregion
#region Twitch
private void OnLoginWithTwitchClicked() {
}
#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 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 Recovery
[Header("Recover Account:"), Tooltip("How long do we want the password to be available, before reverting back to old pass?")]
public float PasswordTimerWaitTime = 900;
// 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)
private string RecoverySendPanelTag = "RecoverySendPanel";
private string RecoveryNewPassPanelTag = "RecoveryNewPassPanel";
private string __EmailTag = "Email3InputField";
private string __PasswordTag = "Password3AInputField";
private string __ConfirmPasswordTag = "ConfirmPassword3BInputField";
private string CancelRecoveryButtonTag = "CancelRecoveryButton";
private string RecoveryLoginButtonTag = "RecoveryLoginButton";
private string ShowExistingPlayerPassTextToggleTag = "ShowExistingPlayerPassTextToggle";
private string ShowExistingPlayerConfirmPassTextToggleTag = "ShowExistingPlayerConfirmPassTextToggle";
private string SendRecoveryPassButtonTag = "SendRecoveryPassButton";
public string ChangePassPanelTag = "ChangePassPanel";
public string ___PasswordTag = "Password4AInputField";
public string ___ConfirmPasswordTag = "ConfirmPassword4BInputField";
public string CloseChangePassPanelTag = "CloseChangePassPanel";
public string SaveNewPassButtonTag = "SaveNewPassButton";
/// <summary>
/// Window that comes up when we need to recover password.
/// </summary>
private GameObject RecoverySendPanel;
/// <summary>
/// Once player has entered correct pass from email, this window opens and the Recovery enter pass closes.
/// </summary>
private GameObject RecoveryNewPassPanel;
/// <summary>
/// If Two Dactor Auth Enabled, this will Pop up upon login.
/// </summary>
private GameObject ChangePassPanel;
/// <summary>
/// Input Field On your Recover Login - Send New Pass.
/// </summary>
private InputField __Email;
/// <summary>
/// Input Field On your Recover Login - EnterPass.
/// </summary>
private InputField __Password;
/// <summary>
/// Input Field On your Recover Login - EnterPass.
/// </summary>
private InputField __ConfirmPassword;
/// <summary>
/// Toggle On your Recover Login - Controls password viewables or not (ContentType: Alphanumeric or Password.
/// </summary>
private Toggle ShowExistingPlayerPassTextToggle;
/// <summary>
/// Toggle On your Recover Login - Controls password viewables or not (ContentType: Alphanumeric or Password.
/// </summary>
private Toggle ShowExistingPlayerConfirmPassTextToggle;
/// <summary>
/// Button to send the new password to players email.
/// </summary>
private Button SendRecoveryPassButton;
/// <summary>
/// Cancel recovery, restore old pass.
/// </summary>
private Button CancelRecoveryButton;
/// <summary>
/// Logs player in and sets new pass from emailed pass. Prompt's change pass window.
/// </summary>
private Button RecoveryLoginButton;
/// <summary>
/// Closes the Change Pass panel and doesn't change the password.
/// </summary>
private Button CloseChangePassPanel;
/// <summary>
/// Closes the Change Pass panel and saves the password.
/// </summary>
private Button SaveNewPassButton;
private bool HasChangedPass = false;
private bool ChangeHeader = false;
private bool timerEnabled;
private string tempPass = "";
private const string glyphs = "abcdefghijklmnopqrstuvwxyz0123456789"; //add the characters you want
private const string PlayersOldPassKey = "StorageKey";
private void OnRecoverSetup()
{
RecoverySendPanel = GameObject.FindGameObjectWithTag(RecoverySendPanelTag);
RecoveryNewPassPanel = GameObject.FindGameObjectWithTag(RecoveryNewPassPanelTag);
ChangePassPanel = GameObject.FindGameObjectWithTag(ChangePassPanelTag);
__Email = GameObject.FindGameObjectWithTag(__EmailTag).GetComponent<InputField>();
__Password = GameObject.FindGameObjectWithTag(__PasswordTag).GetComponent<InputField>();
__ConfirmPassword = GameObject.FindGameObjectWithTag(__ConfirmPasswordTag).GetComponent<InputField>();
ShowExistingPlayerPassTextToggle = GameObject.FindGameObjectWithTag(ShowExistingPlayerPassTextToggleTag).GetComponent<Toggle>();
ShowExistingPlayerConfirmPassTextToggle = GameObject.FindGameObjectWithTag(ShowExistingPlayerConfirmPassTextToggleTag).GetComponent<Toggle>();
SendRecoveryPassButton = GameObject.FindGameObjectWithTag(SendRecoveryPassButtonTag).GetComponent<Button>();
CancelRecoveryButton = GameObject.FindGameObjectWithTag(CancelRecoveryButtonTag).GetComponent<Button>();
RecoveryLoginButton = GameObject.FindGameObjectWithTag(RecoveryLoginButtonTag).GetComponent<Button>();
CloseChangePassPanel = GameObject.FindGameObjectWithTag(CloseChangePassPanelTag).GetComponent<Button>();
SaveNewPassButton = GameObject.FindGameObjectWithTag(SaveNewPassButtonTag).GetComponent<Button>();
RecoveryLoginButton.onClick.AddListener(OnOpenRecoveryClicked);
CancelRecoveryButton.onClick.AddListener(OnCancelRecoveryClicked);
SendRecoveryPassButton.onClick.AddListener(OnSendRecoveryMessageClicked);
CloseChangePassPanel.onClick.AddListener(OnCloseChangePass);
SaveNewPassButton.onClick.AddListener(SaveNewPassword);
}
private void ShowPasswordRecovery()
{
if (ShowExistingPlayerPassTextToggle.isOn)
{
__Password.contentType = InputField.ContentType.Alphanumeric;
}
else {
__Password.contentType = InputField.ContentType.Password;
}
}
private void ShowConfirmPasswordRecovery()
{
if (ShowExistingPlayerConfirmPassTextToggle.isOn)
{
__ConfirmPassword.contentType = InputField.ContentType.Alphanumeric;
}
else {
__ConfirmPassword.contentType = InputField.ContentType.Password;
}
}
private void OnOpenRecoveryClicked() {
CheckIfLoginPanelExists(false);
CheckIfLoggedinPanelExists(false);
CheckIfRecoverySendPanelExists(true);
CheckIfRecoveryNewPassPanelExists(false);
CheckIfRegisterPanelExists(false);
CheckIfChangePassPanelExists(false);
CheckIfDevSettingsPanelExists(false);
}
private void OnSendRecoveryMessageClicked()
{
CheckIfLoginPanelExists(false);
CheckIfLoggedinPanelExists(false);
CheckIfRecoverySendPanelExists(false);
CheckIfRecoveryNewPassPanelExists(true);
CheckIfRegisterPanelExists(false);
CheckIfChangePassPanelExists(false);
CheckIfDevSettingsPanelExists(false);
SaveOldPassword();
OnGenerateNewPass();
SendPlayerAndEmail(password);
StartCoroutine(PasswordTimer(PasswordTimerWaitTime));//Start Timer 15 mins
}
private void OnRecoverLoginClicked() {
ProgressBar.UpdateLabel(string.Format("Registering User {0} ...", UserName.text));
ProgressBar.UpdateProgress(0f);
ProgressBar.AnimateProgress(0, 1, () => {
//second loop
ProgressBar.UpdateProgress(0f);
ProgressBar.AnimateProgress(0, 1, () => {
ProgressBar.UpdateLabel(string.Empty);
ProgressBar.UpdateProgress(0f);
});
});
_AuthService.Username = _UserName.text;
_AuthService.Email = __Email.text;
_AuthService.Password = __Password.text;
_AuthService.Authenticate(Authtypes.None);
GetUsername(_UserName.text);
GetUserPassword(__Password.text);
GetUserEmail(__Email.text);
GetUserPasswordConfirm(__ConfirmPassword.text);
GetStats();
GetPlayerData();
checkUserPass = CheckUserPassword;
if (checkUserPass)
{
var request = new LoginWithCustomIDRequest()
{
TitleId = PlayFabSettings.TitleId,
CustomId = SystemInfo.deviceUniqueIdentifier,
CreateAccount = true
};
PlayFabClientAPI.LoginWithCustomID(request, OnLoginSuccess, OnPlayFabError);
if (isPlayerLoggedIn)
{
PlayFabClientAPI.UpdateUserTitleDisplayName(new UpdateUserTitleDisplayNameRequest { DisplayName = userName }, OnDisplayName, OnPlayFabError);
InitializeNewEncryptionKey(userName, password, email);//Each Player Get's their own encryption for PPs
if (DebugMode)
Debug.LogFormat("Is Player Logged in: {0}", isPlayerLoggedIn);
}
}
else {
if (Instance.DebugMode)
Debug.LogError("Passwords do not match. Nothing happend. This message is In Your 'public void OnLoginClickButton()', but it failed in the 'CheckUserPassword' bool property.");
}
CheckIfLoginPanelExists(false);
CheckIfLoggedinPanelExists(true);
CheckIfRecoverySendPanelExists(false);
CheckIfRecoveryNewPassPanelExists(false);
CheckIfRegisterPanelExists(false);
CheckIfChangePassPanelExists(true);
CheckIfDevSettingsPanelExists(false);
}
private void OnCancelRecoveryClicked()
{
CheckIfLoginPanelExists(true);
CheckIfLoggedinPanelExists(false);
CheckIfRecoverySendPanelExists(false);
CheckIfRecoveryNewPassPanelExists(false);
CheckIfRegisterPanelExists(false);
CheckIfChangePassPanelExists(false);
CheckIfDevSettingsPanelExists(false);
StopPasswordTimer();
}
private void OnCloseChangePass() {
if (HasChangedPass) {
ChangeHeader = true;
}
ChangePassPanel.SetActive(false);
}
private void OnGenerateNewPass()
{
int charAmount = UnityEngine.Random.Range(15, 18); //set those to the minimum and maximum length of your string
for (int i = 0; i < charAmount; i++)//Loops though our random number
{
password += glyphs[UnityEngine.Random.Range(0, glyphs.Length)];// Generate Random Pass
}
if (Instance.DebugMode)
Debug.Log("GenerateNewPass Complete");
}
private void SendPlayerAndEmail(string newPass)
{
if (Instance.DebugMode)
Debug.Log("SendPlayerAndEmail");
}
private void SaveNewPassword()
{
SetString(PlayerPassKey, password);
if (Instance.DebugMode)
Debug.Log("Pass Saved.");
OnCloseChangePass();
}
private void SaveOldPassword()
{
tempPass = password;
password = "";
SetString(PlayersOldPassKey, tempPass);//Stores current state
if (Instance.DebugMode)
Debug.LogFormat("Old Pass Saved for {0} seconds.", PasswordTimerWaitTime);
}
private void StopPasswordTimer()
{
timerEnabled = false;
password = GetString(PlayersOldPassKey, tempPass);
tempPass = "";
tempPass = GetString(PlayersOldPassKey, tempPass);// restore pass
password = tempPass;
Password.text = password;
_Password.text = password;
__Password.text = password;
PlayFabController.DeleteKey(PlayersOldPassKey);
StopCoroutine("PasswordTimer");//Stops the timer
if (Instance.DebugMode)
Debug.Log("StopPasswordTimer");
}
private IEnumerator PasswordTimer(float waitTime)
{
timerEnabled = true;
if (Instance.DebugMode)
Debug.Log("PasswordTimer Started.");
yield return new WaitForSeconds(waitTime);//Time set in the Generate New Pass
if (Instance.DebugMode)
Debug.Log("PasswordTimer Timed Out.");
StopPasswordTimer();
}
#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 PlayerData
//sends a request to get the player data from the playfab cloud
public void GetPlayerData()
{
PlayFabClientAPI.GetUserData(new GetUserDataRequest()
{
PlayFabId = myID,
Keys = null
}, UserDataSuccess, OnErrorLeaderboard);
}
//the return callback function for success.
void UserDataSuccess(GetUserDataResult result)
{
if (result.Data == null || !result.Data.ContainsKey("Skins"))
{
if (Instance.DebugMode)
Debug.Log("Skins not set");
}
else
{
//Get the resutls of the requests and sends it to be converted to the all skins array.
PersistentData.Instance.SkinsStringToData(result.Data["Skins"].Value);
}
}
//Sends a request to save the new player data to the playfab cloud
public void SetSkinsData(string SkinsData)
{
OnSaveSkins(SkinsData);
}
void OnSaveSkins(string SkinsData)
{
PlayFabClientAPI.UpdateUserData(new UpdateUserDataRequest()
{
Data = new Dictionary<string, string>()
{
//key value pair, saving the allskins array as a string to the playfab cloud
{"Skins", SkinsData}
}
}, SetDataSuccess, OnErrorLeaderboard);
}
//return callback function for a successful request
void SetDataSuccess(UpdateUserDataResult result)
{
if (Instance.DebugMode)
Debug.Log(result.DataVersion);
}
#endregion
#region PlayerStats
private int playerLevel;
private int gameScene;
private int playerCurrentScore;
private int playerHighScore;
private int playerFreeCurrency;
private int playerPaidForCurrency;
private int skillPoints_Aim;
private int skillPoints_Range;
private int skillPoints_FiringRate;
private int skillPoints_Payload;
private int rank;
private int tierRank;
private int experience;
private int playerCurrentHealth;
private int playerMaxHealth;
private int playerBaseDamage;
private int playerDamageLeftRocket;
private int playerDamageRightRocket;
private int playerDamageCenterRocket;
private int playerSheild;
private int playerBonusDamage;
private int ShipSelection;
private int Rocket1Selection;
private int Rocket2Selection;
private int Rocket3Selection;
public void SetStats()
{
PlayFabClientAPI.UpdatePlayerStatistics(new UpdatePlayerStatisticsRequest
{
// request.Statistics is a list, so multiple StatisticUpdate objects can be defined if required.
Statistics = new List<StatisticUpdate> {
new StatisticUpdate { StatisticName = "playerLevel", Value = playerLevel },
new StatisticUpdate { StatisticName = "gameScene", Value = gameScene },
new StatisticUpdate { StatisticName = "playerCurrentScore", Value = playerCurrentScore },
new StatisticUpdate { StatisticName = "playerHighScore", Value = playerHighScore },
new StatisticUpdate { StatisticName = "playerFreeCurrency", Value = playerFreeCurrency },
new StatisticUpdate { StatisticName = "playerPaidForCurrency", Value = playerPaidForCurrency },
new StatisticUpdate { StatisticName = "skillPoints_Aim", Value = skillPoints_Aim },
new StatisticUpdate { StatisticName = "skillPoints_Range", Value = skillPoints_Range },
new StatisticUpdate { StatisticName = "skillPoints_FiringRate", Value = skillPoints_FiringRate },
new StatisticUpdate { StatisticName = "skillPoints_Payload", Value = skillPoints_Payload },
new StatisticUpdate { StatisticName = "rank", Value = rank },
new StatisticUpdate { StatisticName = "tierRank", Value = tierRank },
new StatisticUpdate { StatisticName = "experience", Value = experience },
new StatisticUpdate { StatisticName = "playerCurrentHealth", Value = playerCurrentHealth },
new StatisticUpdate { StatisticName = "playerMaxHealth", Value = playerMaxHealth },
new StatisticUpdate { StatisticName = "playerBaseDamage", Value = playerBaseDamage },
new StatisticUpdate { StatisticName = "playerBonusDamage", Value = playerBonusDamage },
new StatisticUpdate { StatisticName = "playerDamageLeftRocket", Value = playerDamageLeftRocket },
new StatisticUpdate { StatisticName = "playerDamageRightRocket", Value = playerDamageRightRocket },
new StatisticUpdate { StatisticName = "playerDamageCenterRocket", Value = playerDamageCenterRocket },
new StatisticUpdate { StatisticName = "playerSheild", Value = playerSheild },
new StatisticUpdate { StatisticName = "ShipSelection", Value = ShipSelection },
new StatisticUpdate { StatisticName = "Rocket1Selection", Value = Rocket1Selection },
new StatisticUpdate { StatisticName = "Rocket2Selection", Value = Rocket2Selection },
new StatisticUpdate { StatisticName = "Rocket3Selection", Value = Rocket3Selection },
}
},
result => { Debug.Log("User statistics updated"); },
error => { Debug.LogError(error.GenerateErrorReport()); });
}
void GetStats()
{
PlayFabClientAPI.GetPlayerStatistics(
new GetPlayerStatisticsRequest(),
OnGetStats,
error => Debug.LogError(error.GenerateErrorReport())
);
}
void OnGetStats(GetPlayerStatisticsResult result)
{
Debug.Log("Received the following Statistics:");
foreach (var eachStat in result.Statistics)
{
if (Instance.DebugMode)
Debug.Log("Statistic (" + eachStat.StatisticName + "): " + eachStat.Value);
switch (eachStat.StatisticName)
{
case "playerLevel":
playerLevel = eachStat.Value;
break;
case "gameScene":
gameScene = eachStat.Value;
break;
case "playerCurrentScore":
playerCurrentScore = eachStat.Value;
break;
case "playerHighScore":
playerHighScore = eachStat.Value;
break;
case "playerFreeCurrency":
playerFreeCurrency = eachStat.Value;
break;
case "playerPaidForCurrency":
playerPaidForCurrency = eachStat.Value;
break;
case "skillPoints_Aim":
skillPoints_Aim = eachStat.Value;
break;
case "skillPoints_Range":
skillPoints_Range = eachStat.Value;
break;
case "skillPoints_FiringRate":
skillPoints_FiringRate = eachStat.Value;
break;
case "skillPoints_Payload":
skillPoints_Payload = eachStat.Value;
break;
case "rank":
rank = eachStat.Value;
break;
case "tierRank":
tierRank = eachStat.Value;
break;
case "experience":
experience = eachStat.Value;
break;
case "playerCurrentHealth":
playerCurrentHealth = eachStat.Value;
break;
case "playerMaxHealth":
playerMaxHealth = eachStat.Value;
break;
case "playerBaseDamage":
playerBaseDamage = eachStat.Value;
break;
case "playerBonusDamage":
playerBonusDamage = eachStat.Value;
break;
case "playerDamageLeftRocket":
playerDamageLeftRocket = eachStat.Value;
break;
case "playerDamageRightRocket":
playerDamageRightRocket = eachStat.Value;
break;
case "playerDamageCenterRocket":
playerDamageCenterRocket = eachStat.Value;
break;
case "playerSheild":
playerSheild = eachStat.Value;
break;
case "ShipSelection":
ShipSelection = eachStat.Value;
break;
case "Rocket1Selection":
Rocket1Selection = eachStat.Value;
break;
case "Rocket2Selection":
Rocket2Selection = eachStat.Value;
break;
case "Rocket3Selection":
Rocket3Selection = eachStat.Value;
break;
}
}
}
// Build the request object and access the API
public void StartCloudUpdatePlayerStats()
{
PlayFabClientAPI.ExecuteCloudScript(new ExecuteCloudScriptRequest()
{
FunctionName = "UpdatePlayerStats", // Arbitrary function name (must exist in your uploaded cloud.js file)
FunctionParameter = new { Level = playerLevel, highScore = playerHighScore, apple = 0 }, // The parameter provided to your function
GeneratePlayStreamEvent = true, // Optional - Shows this event in PlayStream
}, OnCloudUpdateStats, OnErrorShared);
}
// OnCloudHelloWorld defined in the next code block
private static void OnCloudUpdateStats(ExecuteCloudScriptResult result)
{
// Cloud Script returns arbitrary results, so you have to evaluate them one step and one parameter at a time
if (Instance.DebugMode)
Debug.Log(JsonWrapper.SerializeObject(result.FunctionResult));
JsonObject jsonResult = (JsonObject)result.FunctionResult;
object messageValue;
jsonResult.TryGetValue("messageValue", out messageValue); // note how "messageValue" directly corresponds to the JSON values set in Cloud Script
if (Instance.DebugMode)
Debug.Log((string)messageValue);
}
private static void OnErrorShared(PlayFabError error)
{
if (Instance.DebugMode)
Debug.Log(error.GenerateErrorReport());
}
#endregion
}
#endregion
#endregion
using UnityEngine;
using System.Collections;
using System.IO;
public class Settings : Singleton<Settings> {
/**
* Directories routing settings
*/
public static string APP_PATH = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
// ASSETS_PATH determines where static Assets are stored
public static string ASSETS_PATH = "Assets" + Path.DirectorySeparatorChar;
/**
* Language settings
*/
// LANGUAGE_PATH determines where language files are stored
public static string LANGUAGE_PATH = Settings.ASSETS_PATH + "Resources" + Path.DirectorySeparatorChar + "Localizatron" + Path.DirectorySeparatorChar + "Locale" + Path.DirectorySeparatorChar;
public static string SAVING_LANGUAGE_PATH = Path.DirectorySeparatorChar + "Resources" + Path.DirectorySeparatorChar + "Localizatron" + Path.DirectorySeparatorChar + "Locale" + Path.DirectorySeparatorChar;
// LANGUAGE_EXTENSION determines the language files extension
public static string LANGUAGE_EXTENSION = ".txt";
// LANGUAGE_DEFAULT determines the default language code
public static string LANGUAGE_DEFAULT = "en-EN";
}
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;
}
}
#region Licencing
/*
ZeredaGamesEngine
Author:
Zereda Games & Co.
Thamas Bell : thamasbell@hotmail.com
Permission is hereby granted, by purchase of package, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
This permission notice shall be included in all copies or substantial portions of the Code diriving from this software.
*Note: You the customer have purchased this code pack by means of purchase on the unity asset store, and have paid your dues to the developer of this code.
All code within this pack is imbedded and require one another. The pack also comes with all neccessary files for you to include in your pack as an assesory
to your pack. I encurage others to build upon this pack, or include as an addon in the pack, for more developer freedom in the future.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#endregion
#region using
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
#endregion
#region Script
namespace ZeredaGamesEngine.Core.Managers
{
#region Attributes
[ExecuteInEditMode]
[System.Serializable]
#endregion
public class Splashscreen : MonoBehaviour
{
static Image fadeImage;
[Tooltip ("When set to false, loads scene via Custom Scene otherwise it loads the next scene.")]
public bool
UseNextSceneBuildIndex = true;
[Tooltip ("Set this to the scene you would like to load in not the next scene.")]
public int
CustomScene;
static int nextSceneBuildIndex;
[Tooltip ("How long does it take for the image to fade to 1.")]
public float
FadeInLength;
[Tooltip ("How long will it show the scene before it begins to auto fade.")]
public float
ShowSplashImageTimeLengthInSeconds;
[Tooltip ("How long does it take for the image to fade to 0.")]
public float
FadeOutLength;
[Tooltip ("how long after the image fades does it take for the script to load the 'nextSceneBuildIndex' variable set above.")]
public float
TimeInSecondsTillNextScene;
IEnumerator Start ()
{
if (CustomScene != 0) {
UseNextSceneBuildIndex = false;
nextSceneBuildIndex = CustomScene;
} else {
nextSceneBuildIndex = SceneManager.GetActiveScene ().buildIndex + 1;
}
fadeImage = gameObject.transform.Find ("FadeImage").GetComponent<Image> ();
fadeImage.canvasRenderer.SetAlpha (1.0f);
FadeOut ();
yield return new WaitForSecondsRealtime (ShowSplashImageTimeLengthInSeconds);
FadeIn ();
yield return new WaitForSecondsRealtime (TimeInSecondsTillNextScene);
if (UseNextSceneBuildIndex) {
SceneManager.LoadScene (nextSceneBuildIndex);
} else {
SceneManager.LoadScene (CustomScene);
}
}
void FadeIn ()
{
fadeImage.CrossFadeAlpha (1.0f, FadeInLength, false);
}
void FadeOut ()
{
fadeImage.CrossFadeAlpha (0.0f, FadeOutLength, false);
}
}
}
#endregion
#region About
/**
* Company: InfoGamer, ZeredaGames
* Product: Player Login with Playfab
* Bundle Version: V1.0.0.1.0 //Build Version, Major Update, Minor Update, Revision, Patch
* PlayFabController.cs
* Created by: InfoGamer, Revision by ZeredaGames
* Created on: (3/3/2019)
*/
#endregion
#region Licencing
#endregion
#region using
#region Unity
using UnityEngine;
using UnityEngine.UI;
#endregion
#endregion
public class SubtitleController : MonoBehaviour
{
public Text SubtitleText;
}
using UnityEngine;
using System.Collections;
public class TimePause : MonoBehaviour, IPausable {
public float pauseDelay = 0.3f;
private float timeScale;
public void OnUnPause() {
Debug.Log ("TestPause.OnUnPause");
Time.timeScale = timeScale;
}
public void OnPause() {
Debug.Log ("TestPause.OnPause");
timeScale = Time.timeScale;
Invoke ("StopTime", pauseDelay );
}
void StopTime() {
Time.timeScale = 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment