示例#1
0
    void ContinueProcess()
    {
        System.GC.Collect();

        if (GameManager.Instance.Levels != null)
        {
            Level nextLevel = GameManager.Instance.Levels.GetNextItem();

            // no more levels
            if (nextLevel == null)
            {
                BackToLevels();
                return;
            }

            Pack nextLevelPack = LevelController.Instance.PackForLevel(nextLevel);

            if (nextLevelPack != null && !nextLevelPack.IsUnlocked)
            {
                BackToLevels();
                return;
            }

            GameManager.Instance.Levels.Selected = nextLevel;
            PreferencesFactory.Save();

            GameController.Instance.NextLevel();

            return;
        }

        BackToLevels();
    }
    public void SyncProgress()
    {
        if (!IsUserLoggedIn())
        {
            return;
        }

        DateTime now = UnbiasedTime.Instance.Now();

        // when implement void SaveState(), add it here to save state before sync
        CustomFreePrizeManager.Instance.SaveState();
        LevelController.Instance.SaveState();

        PreferencesFactory.SetString("LastProgressSyncDate", now.ToString(CultureInfo.InvariantCulture), false);
        PreferencesFactory.Save();

        string json = JSONPrefs.String();

        GSRequestData parsedJson = new GSRequestData(json);

        new LogEventRequest()
        .SetEventKey("PlayerProgress")
        .SetEventAttribute("data", parsedJson)
        .Send(((response) => {
            if (!response.HasErrors)
            {
                PlayerPrefs.SetString("LastProgressSyncDate", now.ToString(CultureInfo.InvariantCulture));
                PlayerPrefs.Save();
            }
        }));
    }
        /// <summary>
        /// Save the current state including free prize times
        /// </summary>
        public override void SaveState()
        {
            MyDebug.Log("FreePrizeManager: SaveState");

            PreferencesFactory.SetString("FreePrize.NextCountdownStart", NextCountdownStart.ToString(CultureInfo.InvariantCulture));
            PreferencesFactory.SetString("FreePrize.NextPrize", NextFreePrizeAvailable.ToString(CultureInfo.InvariantCulture));
            PreferencesFactory.Save();
        }
示例#4
0
        /// <summary>
        /// Called when an unlocked button is clicked
        /// </summary>
        /// The default implementation sets the GameItemManager's selected item and then if specified loads the scene specified by ClickUnlockedSceneToLoad.
        /// You may override this in a derived class.
        public virtual void ClickUnlocked()
        {
            GetGameItemManager().Selected = CurrentItem;
            PreferencesFactory.Save();

            if (!string.IsNullOrEmpty(ClickUnlockedSceneToLoad))
            {
                GameManager.LoadSceneWithTransitions(string.Format(ClickUnlockedSceneToLoad, CurrentItem.Number));
            }
        }
        /// <summary>
        /// Show a dialog one time only using the specified dialog as a key for identifying this instance.
        /// </summary>
        /// <param name="dialogKey"></param>
        /// <param name="prefab"></param>
        /// <param name="title"></param>
        /// <param name="titleKey"></param>
        /// <param name="text"></param>
        /// <param name="textKey"></param>
        /// <param name="text2"></param>
        /// <param name="text2Key"></param>
        /// <param name="sprite"></param>
        /// <param name="doneCallback"></param>
        /// <param name="dialogButtons"></param>
        /// <returns></returns>
        public DialogInstance ShowOnce(string dialogKey, string prefab = null, string title = null, string titleKey = null, string text = null, string textKey = null, string text2 = null, string text2Key = null, Sprite sprite = null, Action <DialogInstance> doneCallback = null, DialogInstance.DialogButtonsType dialogButtons = DialogInstance.DialogButtonsType.Ok)
        {
            // show hint panel first time only
            if (PreferencesFactory.GetInt("GeneralMessage." + dialogKey, 0) == 0)
            {
                PreferencesFactory.SetInt("GeneralMessage." + dialogKey, 1);
                PreferencesFactory.Save();

                return(Show(prefab, title, titleKey, text, textKey, text2, text2Key, sprite, doneCallback, dialogButtons));
            }
            return(null);
        }
示例#6
0
 /// <summary>
 /// Called when the dialog completes so you can save values or do other adjustments.
 /// </summary>
 /// Check DialogInstance.DialogResult to find out the action that caused the dialog to complete.
 /// Override this in your own base class if you want to customise the settings window. Be sure to call this base instance when done.
 public virtual void DoneCallback(DialogInstance dialogInstance)
 {
     if (DialogInstance.DialogResult == DialogInstance.DialogResultType.Ok)
     {
         // set values not updated automatically
         GameManager.Instance.EffectAudioVolume = _sfxVolume.value;
         PreferencesFactory.Save();
     }
     else
     {
         GameManager.Instance.BackGroundAudioVolume = _oldBackGroundAudioVolume;
     }
 }
示例#7
0
        /// <summary>
        /// Save GameManager state
        /// </summary>
        public override void SaveState()
        {
            MyDebug.Log("GameManager: SaveState");

            PreferencesFactory.SetInt("TimesPlayedForRatingPrompt", TimesPlayedForRatingPrompt);
            PreferencesFactory.SetInt("TimesGamePlayed", TimesGamePlayed);
            PreferencesFactory.SetInt("TimesLevelsPlayed", TimesLevelsPlayed);

            PreferencesFactory.SetFloat("BackGroundAudioVolume", BackGroundAudioVolume, false);
            PreferencesFactory.SetFloat("EffectAudioVolume", EffectAudioVolume, false);

            PreferencesFactory.Save();
        }
示例#8
0
        /// <summary>
        /// Process purchase of a given productId.
        /// </summary>
        /// This automatically handles certain types of purchase and notifications. It is called by PaymentManager but can also be
        /// called from code if needed.
        public static void ProcessPurchase(string productId)
        {
            MyDebug.Log(string.Format("ProcessPurchase: Product: '{0}'", productId));

            if (string.Equals(productId, "android.test.purchased", StringComparison.Ordinal))
            {
                DialogManager.Instance.ShowInfo("Test payment android.test.purchased purchased ok");
            }

            else if (productId.Equals("unlockgame"))
            {
                // update on GameManager
                if (GameManager.IsActive)
                {
                    GameManager.Instance.IsUnlocked = true;
                }

                // ensure it is saved
                PreferencesFactory.SetInt("IsUnlocked", 1);
                PreferencesFactory.Save();

                // notify all subscribers of the purchase
                GameManager.SafeQueueMessage(new UnlockGamePurchasedMessage());
            }

            else if (productId.StartsWith("unlock.world."))
            {
                PurchaseGameItem <World>(productId, "unlock.world.", () => GameManager.Instance.Worlds, number => new WorldPurchasedMessage(number));
            }

            else if (productId.StartsWith("unlock.level."))
            {
                PurchaseGameItem <Level>(productId, "unlock.level.", () => GameManager.Instance.Levels, number => new LevelPurchasedMessage(number));
            }

            else if (productId.StartsWith("unlock.character."))
            {
                PurchaseGameItem <Character>(productId, "unlock.character.", () => GameManager.Instance.Characters, number => new CharacterPurchasedMessage(number));
            }

            else if (productId.StartsWith("unlock.genericgameitem."))
            {
                PurchaseGameItem <GenericGameItem>(productId, "unlock.genericgameitem.", () => GenericGameItemManager.Instance.GenericGameItems, number => new GenericGameItemPurchasedMessage(number));
            }

            // finally send the generic påurchased message.
            GameManager.SafeQueueMessage(new ItemPurchasedMessage(productId));
        }
示例#9
0
        /// <summary>
        /// Called when the GameItem that this button represents is unlocked.
        /// </summary>
        /// The default behaviour will set the Unlock trigger on any attached Animator so you can animation the unlocking.
        /// You may override this method to provide your own custom handling.
        public virtual void Unlock()
        {
            CurrentItem.IsUnlocked = true;
            CurrentItem.IsUnlockedAnimationShown = true;
            CurrentItem.UpdatePlayerPrefs();
            PreferencesFactory.Save();

            Animator animator = GetComponent <Animator>();

            if (animator != null)
            {
                animator.SetTrigger("Unlock");
            }
            else
            {
                SetupDisplay();
            }
        }
示例#10
0
    void CompleteReward()
    {
        var currentLevel = GameManager.Instance.Levels.Selected;
        var points       = currentLevel.Score;

        currentLevel.AddPoints(points);

        GameManager.Instance.Player.AddPoints(points);

        GameManager.Instance.Player.UpdatePlayerPrefs();
        currentLevel.UpdatePlayerPrefs();
        PreferencesFactory.Save();

        UIHelper.SetTextOnChildGameObject(pointsView, "ScoreResult", LocaliseText.Format("LevelCompleted.ScoreDouble", points), true);

        GameObject DoubleButton = GameObjectHelper.GetChildNamedGameObject(pointsView, "DoubleButton", true);

        DoubleButton.SetActive(false);

        GameObject AdsObject = GameObjectHelper.GetChildNamedGameObject(pointsView, "Ads", true);

        AdsObject.SetActive(false);

        GameObject unlockTextObject = GameObjectHelper.GetChildNamedGameObject(pointsView, "UnlockText", true);

        unlockTextObject.SetActive(false);

        GameObject ShareButton = GameObjectHelper.GetChildNamedGameObject(pointsView, "ShareButton", true);

        ShareButton.SetActive(true);

        if (!_multiplayer)
        {
            JSONObject pointsData = new JSONObject();
            pointsData.Add("Level", currentLevel.Number.ToString());
            pointsData.Add("Language", LocaliseText.Language);
            pointsData.Add("RealLanguage", LanguageUtils.RealLanguage(LocaliseText.Language));
            pointsData.Add("Words", JsonUtils.ListToArray(GameController.Instance.GetFoundWords()));
            pointsData.Add("Date", DateTimeUtils.DateTimeToISO8601(UnbiasedTime.Instance.UTCNow()));

            GameSparksManager.Instance.SendPoints(points, "LevelComplete-Double", pointsData);
        }
    }
示例#11
0
    private void UnlockNextLevel()
    {
        var nextLevel = GameManager.Instance.Levels.GetNextItem();

        if (nextLevel == null)
        {
            return;
        }

        if (GameManager.Instance.LevelUnlockMode == GameItem.UnlockModeType.Custom &&
            nextLevel != null)
        {
            nextLevel.IsUnlocked = true;
            nextLevel.UpdatePlayerPrefs();

            // save any settings and preferences.
            PreferencesFactory.Save();
        }
    }
    public static void GenerateMoreLevels()
    {
        int NumberOfAdditionalCreatedLevels = PreferencesFactory.GetInt(Constants.KeyNumberOfAdditionalCreatedLevels);
        int StartupLevels = ((CustomGameManager)CustomGameManager.Instance).StartupLevels;

#if UNITY_EDITOR
        Debug.Log("GenerateMoreLevels: StartupLevels: " + StartupLevels);
        Debug.Log("GenerateMoreLevels: NumberOfAdditionalCreatedLevels before: " + NumberOfAdditionalCreatedLevels);
#endif

        NumberOfAdditionalCreatedLevels += 1;
        GameManager.Instance.Levels.Load(1, StartupLevels + NumberOfAdditionalCreatedLevels, 0, true);

#if UNITY_EDITOR
        Debug.Log("GenerateMoreLevels: NumberOfAdditionalCreatedLevels after: " + NumberOfAdditionalCreatedLevels);
        Debug.Log("GenerateMoreLevels: Total: " + (StartupLevels + NumberOfAdditionalCreatedLevels));
#endif

        PreferencesFactory.SetInt(Constants.KeyNumberOfAdditionalCreatedLevels, NumberOfAdditionalCreatedLevels);
        PreferencesFactory.Save();
    }
        /// <summary>
        /// Show an advert and award the player coins if they complete watching it.
        /// </summary>
        /// <param name="coins"></param>
        public static void ShowWatchAdvertForCoins(int coins)
        {
#if UNITY_ADS
            //TODO only show advert button if actually ready to avoid errors.
            if (Advertisement.IsReady())
            {
                Advertisement.Show(null, new ShowOptions
                {
                    //pause = true,
                    resultCallback = result =>
                    {
                        switch (result)
                        {
                        case (ShowResult.Finished):
                            GameManager.Instance.Player.Coins += coins;
                            GameManager.Instance.Player.UpdatePlayerPrefs();
                            PreferencesFactory.Save();
                            DialogManager.Instance.Show(title: "Coins", text: LocaliseText.Format("Advertising.UnityAds.WatchForCoins.Finished", coins));
                            break;

                        case (ShowResult.Skipped):
                            DialogManager.Instance.Show(title: "Coins", text: LocaliseText.Get("Advertising.UnityAds.WatchForCoins.Skipped"));
                            break;

                        case (ShowResult.Failed):
                            DialogManager.Instance.Show(title: "Coins", text: LocaliseText.Get("Advertising.UnityAds.WatchForCoins.UnableToShow"));
                            break;
                        }
                        Debug.Log(result.ToString());
                    }
                });
            }
            else
            {
                DialogManager.Instance.Show(title: "Error", text: LocaliseText.Get("Advertising.UnityAds.UnableToShow"));
            }
#else
            DialogManager.Instance.ShowInfo("This functionality requires that you enable the standard Unity Ads service.\n\nPlease check our website if you need further help.");
#endif
        }
示例#14
0
        /// <summary>
        /// Update any other items as needed once the current level is won. This includes unlocking subsequent worlds
        /// and levels if so necessary.
        /// </summary>
        public static void ProcessCurrentLevelComplete()
        {
            var player    = GameManager.Instance.Player;
            var nextWorld = IsUsingWorlds() ? GameManager.Instance.Worlds.GetNextItem() : null; // might be null if not using worlds
            var nextLevel = GameManager.Instance.Levels.GetNextItem();

            // is the game won
            if (IsCurrentLevelLastInGame())
            {
                player.IsGameWon = true;
                player.UpdatePlayerPrefs();
            }

            // else is a world won - world load code will automatically unlock the first level if needed.
            else if (IsCurrentLevelLastInWorld())
            {
                if (nextWorld != null && nextWorld.UnlockWithCompletion)
                {
                    nextWorld.IsUnlocked = true;
                    nextWorld.UpdatePlayerPrefs();
                }
            }

            // else is at least a level won
            else
            {
                if (nextLevel != null && nextLevel.UnlockWithCompletion)
                {
                    nextLevel.IsUnlocked = true;
                    nextLevel.UpdatePlayerPrefs();
                }
            }

            // save any settings and preferences.
            PreferencesFactory.Save();
        }
示例#15
0
    public void ClaimAwards()
    {
//		if ( _awards.ContainsKey ("unlockedLevels") ) {
//			bool unlocked = LevelController.Instance.UnlockNextPack ();
//
//			if ( unlocked ) {
//				MyDebug.Log ("Award: Unlocked levels: Unlock next pack");
//			}
//
//			if ( !unlocked ) {
//				LevelController.GenerateMoreLevels ();
//
//				int levels = LevelController.TotalLevels ();
//				LevelController.UnlockLevel ((levels - LevelController.levelsPerPage) + 1);
//
//				MyDebug.Log ("Award: Unlocked levels: Unlock additional levels: " + levels);
//			}
//		}

        if (_awards.ContainsKey("noAds"))
        {
            PreferencesFactory.SetInt(Constants.KeyNoAds, 1);

            MyDebug.Log("Award: No Ads: " + PreferencesFactory.GetInt(Constants.KeyNoAds));
        }

        if (_awards.ContainsKey("coins"))
        {
            GameManager.Instance.Player.AddCoins((int)_awards.GetNumber("coins"));

            MyDebug.Log("Award: Coins: " + (int)_awards.GetNumber("coins"));
        }

        if (_awards.ContainsKey("unlockLevel"))
        {
            Level level = GameManager.Instance.Levels.GetItem((int)_awards.GetNumber("unlockLevel"));

            if (level != null)
            {
                level.IsUnlocked = true;
                level.UpdatePlayerPrefs();

                Pack pack = LevelController.Instance.PackForLevel(level);

                if (pack != null)
                {
                    LevelController.Instance.UnlockPack(pack);
                }

                GameManager.Instance.Levels.Selected = level;
            }
        }

        if (_awards.ContainsKey("unlockPack"))
        {
            Pack pack = ((CustomGameManager)CustomGameManager.Instance).Packs.GetItem((int)_awards.GetNumber("unlockPack"));

            if (pack != null)
            {
                LevelController.Instance.UnlockPack(pack);
            }
        }

        if (_awards.ContainsKey("unlockAll"))
        {
            LevelController.Instance.UnlockAll();
        }

        GameManager.Instance.Player.UpdatePlayerPrefs();
        PreferencesFactory.Save();

        _awards = null;

        DialogInstance dialogInstance = gameObject.GetComponent <DialogInstance> ();

        dialogInstance.Done();
    }
示例#16
0
    bool ItemPurchasedHandler(BaseMessage message)
    {
        ItemPurchasedMessage msg = message as ItemPurchasedMessage;

        PaymentProductCoins[] coins = CustomPaymentManager.Coins;
        for (int i = 0; i < coins.Length; i++)
        {
            if (coins[i].Product.Name.Equals(msg.ProductID))
            {
                if (coins [i].Coins > 0)
                {
                    GameObject animatedCoins = GameObject.Find("AddCoinsAnimated");

                    if (animatedCoins != null)
                    {
                        GameObject       addCoinsClone = Instantiate(animatedCoins, animatedCoins.transform.parent);
                        AddCoinsAnimated addCoins      = addCoinsClone.GetComponent <AddCoinsAnimated>();

                        addCoins.AnimateCoinsAdding(coins [i].Coins);
                    }
                    else
                    {
                        GameManager.Instance.Player.AddCoins(coins [i].Coins);
                        GameManager.Instance.Player.UpdatePlayerPrefs();
                    }
                }

                if (coins[i].NoAds == 1)
                {
                    PreferencesFactory.SetInt(Constants.KeyNoAds, 1);
                }

                PreferencesFactory.Save();

                if (!Debug.isDebugBuild)
                {
                    Flurry.Flurry.Instance.LogEvent(coins [i].EventCode);
                    Fabric.Answers.Answers.LogPurchase(coins [i].Price,
                                                       coins [i].Currency,
                                                       true,
                                                       coins [i].Description,
                                                       coins [i].NoAds == 1 ? "Ads" : "Coins",
                                                       msg.ProductID
                                                       );
                    Branch.userCompletedAction("InApp");
                }

                if (GameSparksManager.IsUserLoggedIn())
                {
                    GSRequestData json = new GSRequestData();
                    json.Add("package", msg.ProductID);
                    json.Add("price", string.Format("{0} {1}", coins[i].Price, coins[i].Currency));
                    json.Add("date", DateTime.UtcNow.ToString(CultureInfo.InvariantCulture));

                    new LogEventRequest()
                    .SetEventKey("IAPPurchase")
                    .SetEventAttribute("data", json)
                    .Send(((response) => {
                    }));
                }

                if (coins[i].NoAds == 1)
                {
                    DialogManager.Instance.Show(prefabName: "GeneralMessageOkButton",
                                                title: LocaliseText.Get("Text.Success"),
                                                text: LocaliseText.Get("Payment.PurchaseSuccess"),
                                                dialogButtons: DialogInstance.DialogButtonsType.Ok);
                }

                break;
            }
        }

        return(true);
    }
示例#17
0
        /// <summary>
        /// Shows the game over dialog.
        /// </summary>
        /// Override this in your own base class if you want to customise the game over window. Be sure to call this base instance when done.
        public virtual void Show(bool isWon)
        {
            Assert.IsTrue(LevelManager.IsActive, "Ensure that you have a LevelManager component attached to your scene.");

            var currentLevel = GameManager.Instance.Levels.Selected;

            // update the player score if necessary
            if ((UpdatePlayerScore == CopyType.Always) || (UpdatePlayerScore == CopyType.OnWin && isWon))
            {
                GameManager.Instance.Player.AddPoints(currentLevel.Score);
            }

            // update the player coins if necessary
            if ((UpdatePlayerCoins == CopyType.Always) || (UpdatePlayerCoins == CopyType.OnWin && isWon))
            {
                GameManager.Instance.Player.AddCoins(currentLevel.Coins);
            }

            // show won / lost game objects as appropriate
            GameObjectHelper.SafeSetActive(GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "Lost", true), !isWon);

            // see if the world or game is won and also if we should unlock the next world / level
            GameObjectHelper.SafeSetActive(GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "GameWon", true), false);
            GameObjectHelper.SafeSetActive(GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "WorldWon", true), false);
            GameObjectHelper.SafeSetActive(GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "LevelWon", true), false);
            GameObjectHelper.SafeSetActive(GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "Won", true), false);
            if (isWon)
            {
                //TODO: if coins unlock mode then need to check all levels are done before saying world complete - same for game...
                //TODO: perhaps in future we might want to distinguish between the first and subsequent times a user completes something?
                //// is the game won
                //if (GameHelper.IsCurrentLevelLastInGame()) {
                //    GameObjectHelper.SafeSetActive(GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "GameWon", true), true);
                //}

                //// is a world won
                //else if (GameHelper.IsCurrentLevelLastInGame())
                //{
                //    GameObjectHelper.SafeSetActive(GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "WorldWon", true), true);
                //}

                //// level won
                //else if (GameManager.Instance.Levels.GetNextItem() != null)
                //{
                //    GameObjectHelper.SafeSetActive(GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "LevelWon", true), true);
                //}

                //// else won with some other condition
                //else
                //{
                GameObjectHelper.SafeSetActive(GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "Won", true), true);
                //}

                // process and update game state - do this last so we can check some bits above.
                GameHelper.ProcessCurrentLevelComplete();
            }

            // set some text based upon the result
            UIHelper.SetTextOnChildGameObject(DialogInstance.gameObject, "AchievementText", LocaliseText.Format(LocalisationBase + ".Achievement", currentLevel.Score, currentLevel.Name));

            // setup stars
            var starsGameObject = GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "Stars", true);

            GameObjectHelper.SafeSetActive(starsGameObject, ShowStars);
            if (ShowStars)
            {
                Assert.IsNotNull(starsGameObject, "GameOver->ShowStars is enabled, but could not find a 'Stars' gameobject. Disable the option or fix the structure.");
                starsGameObject.SetActive(ShowStars);
                var newStarsWon = GetNewStarsWon();
                currentLevel.StarsWon |= newStarsWon;
                var star1WonGameObject = GameObjectHelper.GetChildNamedGameObject(starsGameObject, "Star1", true);
                var star2WonGameObject = GameObjectHelper.GetChildNamedGameObject(starsGameObject, "Star2", true);
                var star3WonGameObject = GameObjectHelper.GetChildNamedGameObject(starsGameObject, "Star3", true);
                StarWon(currentLevel.StarsWon, newStarsWon, star1WonGameObject, 1);
                StarWon(currentLevel.StarsWon, newStarsWon, star2WonGameObject, 2);
                StarWon(currentLevel.StarsWon, newStarsWon, star3WonGameObject, 4);
                GameObjectHelper.SafeSetActive(GameObjectHelper.GetChildNamedGameObject(starsGameObject, "StarWon", true), newStarsWon != 0);
            }

            // set time
            var difference     = DateTime.Now - LevelManager.Instance.StartTime;
            var timeGameObject = GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "Time", true);

            GameObjectHelper.SafeSetActive(timeGameObject, ShowTime);
            if (ShowTime)
            {
                Assert.IsNotNull(timeGameObject, "GameOver->ShowTime is enabled, but could not find a 'Time' gameobject. Disable the option or fix the structure.");

                UIHelper.SetTextOnChildGameObject(timeGameObject, "TimeResult", difference.Minutes.ToString("D2") + "." + difference.Seconds.ToString("D2"), true);
            }

            // set coins
            var coinsGameObject = GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "Coins", true);

            GameObjectHelper.SafeSetActive(coinsGameObject, ShowCoins);
            if (ShowCoins)
            {
                Assert.IsNotNull(coinsGameObject, "GameOver->ShowCoins is enabled, but could not find a 'Coins' gameobject. Disable the option or fix the structure.");
                UIHelper.SetTextOnChildGameObject(coinsGameObject, "CoinsResult", currentLevel.Coins.ToString(), true);
            }

            // set score
            var scoreGameObject = GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "Score", true);

            GameObjectHelper.SafeSetActive(scoreGameObject, ShowScore);
            if (ShowScore)
            {
                Assert.IsNotNull(scoreGameObject, "GameOver->ShowScore is enabled, but could not find a 'Score' gameobject. Disable the option or fix the structure.");
                var distanceText = LocaliseText.Format(LocalisationBase + ".ScoreResult", currentLevel.Score.ToString());
                if (currentLevel.HighScore > currentLevel.OldHighScore)
                {
                    distanceText += "\n" + LocaliseText.Get(LocalisationBase + ".NewHighScore");
                }
                UIHelper.SetTextOnChildGameObject(scoreGameObject, "ScoreResult", distanceText, true);
            }

            UpdateNeededCoins();

            // save game state.
            GameManager.Instance.Player.UpdatePlayerPrefs();
            currentLevel.UpdatePlayerPrefs();
            PreferencesFactory.Save();

            //show dialog
            DialogInstance.Show();

            //TODO bug - as we increase TimesPlayedForRatingPrompt on both game start (GameManager) and level finish we can miss this comparison.
            if (GameManager.Instance.TimesPlayedForRatingPrompt == TimesPlayedBeforeRatingPrompt)
            {
                var gameFeedback = new GameFeedback();
                gameFeedback.GameFeedbackAssumeTheyLikeOptional();
            }

#if UNITY_ANALYTICS
            // record some analytics on the level played
            var values = new Dictionary <string, object>
            {
                { "score", currentLevel.Score },
                { "Coins", currentLevel.Coins },
                { "time", difference },
                { "level", currentLevel.Number }
            };
            Analytics.CustomEvent("GameOver", values);
#endif

            // co routine to periodic updates of display (don't need to do this every frame)
            if (!Mathf.Approximately(PeriodicUpdateDelay, 0))
            {
                StartCoroutine(PeriodicUpdate());
            }
        }
示例#18
0
    public void ConnectedWithFacebook()
    {
        if (FacebookManager.Instance.IsLoggedIn)
        {
            if (!GS.Available)
            {
                GS.Reconnect();
            }

            new FacebookConnectRequest()
            .SetAccessToken(AccessToken.CurrentAccessToken.TokenString)
            .SetDoNotLinkToCurrentPlayer(false)
            .SetSwitchIfPossible(true)
            .Send((response) => {
                if (!response.HasErrors)
                {
                    var scriptData = response.ScriptData;
                    if (scriptData != null)
                    {
                        var avatar = scriptData.GetString("avatar");

                        if (avatar != null)
                        {
                            PreferencesFactory.SetString(Constants.ProfileAvatar, avatar);
                        }
                    }

                    var displayName = response.DisplayName;
                    var userId      = response.UserId;

                    PreferencesFactory.SetString(Constants.ProfileUsername, displayName);
                    PreferencesFactory.SetString(Constants.ProfileUserId, response.UserId);
                    PreferencesFactory.SetString(Constants.ProfileFBUserId, AccessToken.CurrentAccessToken.UserId);
                    PreferencesFactory.Save();

                    if (_callback != null)
                    {
                        _callback.OnUserLoggedIn();
                    }

                    if (response.NewPlayer == true)
                    {
                        GameManager.SafeQueueMessage(new UserRegisterMessage());

                        if (!Debug.isDebugBuild)
                        {
                            Fabric.Answers.Answers.LogSignUp("Facebook");
                            Branch.userCompletedAction("RegisterFacebook");
                            Branch.setIdentity(PreferencesFactory.GetString(Constants.ProfileUserId));
                        }
                    }
                    else
                    {
                        GameManager.SafeQueueMessage(new UserLoginMessage());

                        if (!Debug.isDebugBuild)
                        {
                            Fabric.Answers.Answers.LogLogin("Facebook");
                            Branch.userCompletedAction("LoginFacebook");
                            Branch.setIdentity(PreferencesFactory.GetString(Constants.ProfileUserId));
                        }
                    }

                    if (!Debug.isDebugBuild)
                    {
                        Flurry.Flurry.Instance.LogEvent("Register_Facebook");
                    }
                }
                else
                {
                    MyDebug.Log(response.Errors.JSON.ToString());
                    ParseServerResponse(response.Errors);
                }
            });
        }
    }
示例#19
0
    public void RegisterAction(GameObject GO)
    {
        var mainTransform  = GO.transform;
        var email          = mainTransform.Find("EmailField").GetComponent <InputField> ();
        var username       = mainTransform.Find("UsernameField").GetComponent <InputField> ();
        var password       = mainTransform.Find("PasswordField").GetComponent <InputField> ();
        var repearPassword = mainTransform.Find("RepeatPasswordField").GetComponent <InputField> ();

        var emailString    = email.text;
        var usernameString = username.text;
        var passwordString = password.text;
        var repeatString   = repearPassword.text;

        if (string.IsNullOrEmpty(emailString))
        {
            ShowInfoDialogWithText(LocaliseText.Get("Account.EmailEmptyError"), "OK");
            return;
        }
        if (!IsMailValid(emailString))
        {
            ShowInfoDialogWithText(LocaliseText.Get("Account.EmailNotValidError"), "OK");
            return;
        }
        if (string.IsNullOrEmpty(usernameString))
        {
            ShowInfoDialogWithText(LocaliseText.Get("Account.UsernameEmptyError"), "OK");
            return;
        }
        if (!IsUsernameValid(usernameString))
        {
            ShowInfoDialogWithText(LocaliseText.Get("Account.UsernameNotValid"), "OK");
            return;
        }
        if (string.IsNullOrEmpty(passwordString))
        {
            ShowInfoDialogWithText(LocaliseText.Get("Account.PasswordEmptyError"), "OK");
            return;
        }
        if (string.IsNullOrEmpty(repeatString) || !repeatString.Equals(passwordString))
        {
            ShowInfoDialogWithText(LocaliseText.Get("Account.PasswordsNotEqual"), "OK");
            return;
        }

        if (!Reachability.Instance.IsReachable())
        {
            ShowInfoDialogWithText(LocaliseText.Get("Account.NoConnection"), "CLOSE");
            return;
        }

        if (!GS.Available)
        {
            GS.Reconnect();
        }

        Loading.Instance.Show();

        // user was logged from DeviceAuthenticationRequest and now only update his data
        if (PreferencesFactory.HasKey(Constants.ProfileAnonymousUserId))
        {
            new ChangeUserDetailsRequest()
            .SetDisplayName(usernameString)
            .SetUserName(emailString)
            .SetNewPassword(passwordString)
            .Send((response) => {
                Loading.Instance.Hide();

                if (response.HasErrors)
                {
                    ParseServerResponse(response.Errors);
                    return;
                }

                email.text          = null;
                username.text       = null;
                password.text       = null;
                repearPassword.text = null;

                PreferencesFactory.SetString(Constants.ProfileEmail, emailString);
                PreferencesFactory.SetString(Constants.ProfileUsername, usernameString);
                PreferencesFactory.SetString(Constants.ProfileUserId, PreferencesFactory.GetString(Constants.ProfileAnonymousUserId));
                PreferencesFactory.DeleteKey(Constants.ProfileAnonymousUserId);
                PreferencesFactory.Save();

                if (_callback != null)
                {
                    _callback.OnUserRegistered();
                }
                GameManager.SafeQueueMessage(new UserRegisterMessage());

                if (!Debug.isDebugBuild)
                {
                    Flurry.Flurry.Instance.LogEvent("Register_Email");
                    Fabric.Answers.Answers.LogSignUp("Email");
                    Branch.userCompletedAction("Register");
                    Branch.setIdentity(PreferencesFactory.GetString(Constants.ProfileUserId));
                }
            });

            return;
        }

        new RegistrationRequest()
        .SetUserName(emailString)
        .SetDisplayName(usernameString)
        .SetPassword(passwordString)
        .Send(((response) => {
            Loading.Instance.Hide();

            if (!response.HasErrors)
            {
                email.text = null;
                username.text = null;
                password.text = null;
                repearPassword.text = null;

                var scriptData = response.ScriptData;
                if (scriptData != null)
                {
                    var avatar = scriptData.GetString("avatar");

                    if (avatar != null)
                    {
                        PreferencesFactory.SetString(Constants.ProfileAvatar, avatar);
                    }
                }

                PreferencesFactory.SetString(Constants.ProfileEmail, emailString);
                PreferencesFactory.SetString(Constants.ProfileUsername, response.DisplayName);
                PreferencesFactory.SetString(Constants.ProfileUserId, response.UserId);
                PreferencesFactory.Save();

                if (_callback != null)
                {
                    _callback.OnUserRegistered();
                }
                GameManager.SafeQueueMessage(new UserRegisterMessage());

                if (!Debug.isDebugBuild)
                {
                    Flurry.Flurry.Instance.LogEvent("Register_Email");
                    Fabric.Answers.Answers.LogSignUp("Email");
                    Branch.userCompletedAction("Register");
                    Branch.setIdentity(PreferencesFactory.GetString(Constants.ProfileUserId));
                }
            }
            else
            {
                ParseServerResponse(response.Errors);
            }
        }));
    }
示例#20
0
    public void LoginAction(GameObject GO)
    {
        var mainTransform = GO.transform;
        var email         = mainTransform.Find("EmailField").GetComponent <InputField> ();
        var password      = mainTransform.Find("PasswordField").GetComponent <InputField> ();

        var emailString    = email.text;
        var passwordString = password.text;

        if (string.IsNullOrEmpty(emailString))
        {
            ShowInfoDialogWithText(LocaliseText.Get("Account.EmailEmptyError"), "CLOSE");
            return;
        }
        if (!IsMailValid(emailString))
        {
            ShowInfoDialogWithText(LocaliseText.Get("Account.EmailNotValidError"), "CLOSE");
            return;
        }
        if (string.IsNullOrEmpty(passwordString))
        {
            ShowInfoDialogWithText(LocaliseText.Get("Account.PasswordEmptyError"), "CLOSE");
            return;
        }

        if (!Reachability.Instance.IsReachable())
        {
            ShowInfoDialogWithText(LocaliseText.Get("Account.NoConnection"), "CLOSE");
            return;
        }

        if (!GS.Available)
        {
            GS.Reconnect();
        }

        Loading.Instance.Show();

        new AuthenticationRequest()
        .SetUserName(emailString)
        .SetPassword(passwordString)
        .Send(((response) => {
            Loading.Instance.Hide();

            if (!response.HasErrors)
            {
                email.text = null;
                password.text = null;

                var scriptData = response.ScriptData;
                if (scriptData != null)
                {
                    var avatar = scriptData.GetString("avatar");

                    if (avatar != null)
                    {
                        PreferencesFactory.SetString(Constants.ProfileAvatar, avatar);
                    }
                }

                var username = response.DisplayName;
                PreferencesFactory.SetString(Constants.ProfileUsername, username);
                PreferencesFactory.SetString(Constants.ProfileUserId, response.UserId);
                PreferencesFactory.SetString(Constants.ProfileEmail, emailString);
                PreferencesFactory.Save();

                if (_callback != null)
                {
                    _callback.OnUserLoggedIn();
                }

                GameManager.SafeQueueMessage(new UserLoginMessage());

                if (!Debug.isDebugBuild)
                {
                    Fabric.Answers.Answers.LogLogin("Email");
                    Branch.userCompletedAction("Login");
                    Branch.setIdentity(PreferencesFactory.GetString(Constants.ProfileUserId));
                }
            }
            else
            {
                ParseServerResponse(response.Errors);
            }
        }));
    }
示例#21
0
    public virtual void Show(bool isWon, float time, int points = 0, ChallengeManager.GameStates gameState = ChallengeManager.GameStates.Leaved, ChallengeManager.GameStateMessage message = null)
    {
        _multiplayer = GameSparksManager.Instance.GetGameMode() == GameMode.Multi;

        _buttonPurchaseObject = GameObject.Find("PurchaseButton");

        if (_buttonPurchaseObject != null && !_multiplayer)
        {
            _inviteOriginalParent   = _buttonPurchaseObject.transform.parent.gameObject;
            _inviteOriginalPosition = _buttonPurchaseObject.transform.position;

            _inviteButtonObject = gameObject;
            DialogInstance _inviteDialogInstance = gameObject.GetComponent <DialogInstance>();

            GameObjectUtils.MoveObjectToAtIndex(_buttonPurchaseObject, _inviteDialogInstance.Target, 1);
        }

        pointsView      = GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "PointsView", true);
        shareView       = GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "SharingView", true);
        multiplayerView = GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "MultiplayerPointsView", true);

        if (_multiplayer)
        {
            pointsView.SetActive(false);
            multiplayerView.SetActive(true);

            if (gameState == ChallengeManager.GameStates.Won || gameState == ChallengeManager.GameStates.Draw)
            {
                ButtonUtils.PlayWinSound();
            }
            else
            {
                ButtonUtils.PlayLoseSound();
            }
        }
        else
        {
            pointsView.SetActive(true);
            multiplayerView.SetActive(false);

            ButtonUtils.PlayWinSound();
        }

        var currentLevel = GameManager.Instance.Levels.Selected;

        int  coins           = 0;
        bool firstTimePlayed = _multiplayer ? true : currentLevel.ProgressBest < 0.9f;

        LevelManager.Instance.EndLevel();

        this.Coins = coins;

        if (firstTimePlayed && !_multiplayer)
        {
            currentLevel.AddPoints(points);
            currentLevel.ProgressBest = 1.0f;
        }

        if (_multiplayer && gameState == ChallengeManager.GameStates.Lost)
        {
            points *= -1;
        }

        GameObjectHelper.SafeSetActive(GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "Dialog", true), false);

        Assert.IsTrue(LevelManager.IsActive, "Ensure that you have a LevelManager component attached to your scene.");

        if (coins > 0 && !_multiplayer)
        { // add coins for this level
            currentLevel.AddCoins(coins);
            GameManager.Instance.Player.AddCoins(coins);
        }

        GameManager.Instance.Player.AddPoints(points);

        // update the player coins if necessary
        if (((UpdatePlayerCoins == CopyType.Always) || (UpdatePlayerCoins == CopyType.OnWin && isWon)) && !_multiplayer)
        {
            GameManager.Instance.Player.AddCoins(currentLevel.Coins);
        }

        // show won / lost game objects as appropriate
        GameObjectHelper.SafeSetActive(GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "Lost", true), !isWon);

        // see if the world or game is won and also if we should unlock the next world / level
        GameObjectHelper.SafeSetActive(GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "GameWon", true), false);
        GameObjectHelper.SafeSetActive(GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "WorldWon", true), false);
        GameObjectHelper.SafeSetActive(GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "LevelWon", true), false);
        GameObjectHelper.SafeSetActive(GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "Won", true), false);

        GameObject levelName = GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "LevelName", true);

        if (_multiplayer)
        {
            levelName.GetComponent <Text>().text = LocaliseText.Get("LevelCompleted.Match");
        }
        else
        {
            levelName.GetComponent <Text>().text = LocaliseText.Format("LevelCompleted.LevelName", currentLevel.Number);
        }

        GameObjectHelper.SafeSetActive(levelName, true);

        if (!_multiplayer && isWon)
        {
            GameObjectHelper.SafeSetActive(GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "Won", true), true);

            // process and update game state - do this last so we can check some bits above.
            GameHelper.ProcessCurrentLevelComplete();
        }

        // set some text based upon the result
        UIHelper.SetTextOnChildGameObject(DialogInstance.gameObject, "AchievementText", LocaliseText.Format(LocalisationBase + ".Achievement", currentLevel.Score, currentLevel.Name));

        // setup stars
        var starsGameObject = GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "Stars", true);

        GameObjectHelper.SafeSetActive(starsGameObject, ShowStars);
        if (ShowStars && !_multiplayer)
        {
            Assert.IsNotNull(starsGameObject, "GameOver->ShowStars is enabled, but could not find a 'Stars' gameobject. Disable the option or fix the structure.");
            starsGameObject.SetActive(ShowStars);
            var newStarsWon = GetNewStarsWon();
            currentLevel.StarsWon |= newStarsWon;
            var star1WonGameObject = GameObjectHelper.GetChildNamedGameObject(starsGameObject, "Star1", true);
            var star2WonGameObject = GameObjectHelper.GetChildNamedGameObject(starsGameObject, "Star2", true);
            var star3WonGameObject = GameObjectHelper.GetChildNamedGameObject(starsGameObject, "Star3", true);
            StarWon(currentLevel.StarsWon, newStarsWon, star1WonGameObject, 1, coins);
            StarWon(currentLevel.StarsWon, newStarsWon, star2WonGameObject, 2, coins);
            StarWon(currentLevel.StarsWon, newStarsWon, star3WonGameObject, 4, coins);
            GameObjectHelper.SafeSetActive(GameObjectHelper.GetChildNamedGameObject(starsGameObject, "StarWon", true), newStarsWon != 0);
        }

        // set time

        var timeGameObject = GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "Time", true);

        GameObjectHelper.SafeSetActive(timeGameObject, ShowTime);
        if (!_multiplayer && ShowTime)
        {
            TimeSpan timeSpan = TimeSpan.FromSeconds(time);

            string timeText = LocaliseText.Format("LevelCompleted.Time", timeSpan.Minutes, timeSpan.Seconds);

            Assert.IsNotNull(timeGameObject, "GameOver->ShowTime is enabled, but could not find a 'Time' gameobject. Disable the option or fix the structure.");

            UIHelper.SetTextOnChildGameObject(timeGameObject, "TimeResult", timeText, true);
        }

        if (!_multiplayer && currentLevel.TimeBest < 0.05)
        { // save only first time played
            currentLevel.TimeBest = time;
        }

        // set coins
        if (ShowCoins && coins > 0)
        {
            var coinsGameObject = GameObjectHelper.GetChildNamedGameObject(DialogInstance.gameObject, "Coins", true);
            GameObjectHelper.SafeSetActive(coinsGameObject, ShowCoins);

            Assert.IsNotNull(coinsGameObject, "GameOver->ShowCoins is enabled, but could not find a 'Coins' gameobject. Disable the option or fix the structure.");
            UIHelper.SetTextOnChildGameObject(coinsGameObject, "CoinsResult", coins.ToString(), true);
        }

        if (!_multiplayer)
        {
            if (firstTimePlayed)
            {
                GameObject DoubleButton = GameObjectHelper.GetChildNamedGameObject(pointsView, "DoubleButton", true);
                DoubleButton.SetActive(Reachability.Instance.IsReachable());
            }
            else
            {
                GameObject ShareButton = GameObjectHelper.GetChildNamedGameObject(pointsView, "ShareButton", true);
                ShareButton.SetActive(true);
            }
        }

        // set score
        var scoreGameObject = GameObjectHelper.GetChildNamedGameObject(_multiplayer ? multiplayerView : pointsView, "Score", true);

        GameObjectHelper.SafeSetActive(scoreGameObject, ShowScore);

        if (!firstTimePlayed)
        {
            GameObjectHelper.SafeSetActive(scoreGameObject, false);
        }

        if (!_multiplayer && firstTimePlayed)
        {
            GameObject adsObject  = GameObjectHelper.GetChildNamedGameObject(pointsView, "Ads", true);
            Text       unlockText = GameObjectHelper.GetChildComponentOnNamedGameObject <Text>(pointsView, "UnlockText", true);

            if (LevelController.Instance.LastLevelInPack(currentLevel))
            {
                Pack pack     = LevelController.Instance.PackForLevel(currentLevel);
                Pack nextPack = LevelController.Packs().GetItem(pack.Number + 1);

                if (nextPack)
                {
                    nextPack.LoadData();

                    adsObject.SetActive(false);
                    unlockText.gameObject.SetActive(true);

                    unlockText.text = LocaliseText.Format("LevelCompleted.LastLevelInPack", LocaliseText.Get(nextPack.JsonData.GetString("name")));
                }
            }

            if (LevelController.Instance.LastLevelInRank(currentLevel))
            {
                Rank rank     = LevelController.Instance.RankForLevel(currentLevel);
                Rank nextRank = LevelController.Ranks().GetItem(rank.Number + 1);

                if (nextRank)
                {
                    nextRank.LoadData();

                    adsObject.SetActive(false);
                    unlockText.gameObject.SetActive(true);

                    unlockText.text = LocaliseText.Format("LevelCompleted.LastLevelInRank", LocaliseText.Get(nextRank.JsonData.GetString("name")));
                }
            }
        }

        if (ShowScore)
        {
            Assert.IsNotNull(scoreGameObject, "GameOver->ShowScore is enabled, but could not find a 'Score' gameobject. Disable the option or fix the structure.");

            UIHelper.SetTextOnChildGameObject(scoreGameObject, "ScoreResult", LocaliseText.Format("LevelCompleted.Score", "0"), true);

            AnimateScoreText(points);
        }

        if (_multiplayer)
        {
            var resultStateObject = GameObjectHelper.GetChildNamedGameObject(multiplayerView, "ResultState", true);
            GameObjectHelper.SafeSetActive(resultStateObject, true);

            string text = "";

            switch (gameState)
            {
            case ChallengeManager.GameStates.Won:
                text = LocaliseText.Get("Game.YouWon");
                break;

            case ChallengeManager.GameStates.Lost:
                text = LocaliseText.Get("Game.YouLost");
                break;

            case ChallengeManager.GameStates.Draw:
                text = LocaliseText.Get("Game.ItsDrawn");
                break;
            }

            resultStateObject.GetComponent <Text>().text = text;
        }

        if (!_multiplayer)
        {
            UpdateNeededCoins();

            LevelController.Instance.PackProgressCompleted(currentLevel);
            UnlockNextLevel();

            //

            int StartupLevels = ((CustomGameManager)CustomGameManager.Instance).StartupLevels;

            if (StartupLevels == currentLevel.Number)
            {
                GameObject adsObject = GameObjectHelper.GetChildNamedGameObject(pointsView, "Ads", true);

                Text adsText = adsObject.GetComponent <Text>();

                adsText.text                 = LocaliseText.Get("Text.PlayedAllLevels");
                adsText.fontSize             = 39;
                adsText.resizeTextForBestFit = false;

                if (!Debug.isDebugBuild)
                {
                    Flurry.Flurry.Instance.LogEvent("Game_LastLevel", new Dictionary <string, string>()
                    {
                        { "Level", currentLevel.Number.ToString() }
                    });
                    Fabric.Answers.Answers.LogCustom("Game_LastLevel", new Dictionary <string, object>()
                    {
                        { "Level", currentLevel.Number.ToString() }
                    });
                }
            }
        }

        if (!_multiplayer && firstTimePlayed)
        {
            JSONObject pointsData = new JSONObject();
            pointsData.Add("Level", currentLevel.Number.ToString());
            pointsData.Add("Language", LocaliseText.Language);
            pointsData.Add("RealLanguage", LanguageUtils.RealLanguage(LocaliseText.Language));
            pointsData.Add("Time", time.ToString());
            pointsData.Add("UsedHints", GameController.Instance.usedHintsCount);
            pointsData.Add("UserCoins", GameManager.Instance.Player.Coins);
            pointsData.Add("Words", JsonUtils.ListToArray(GameController.Instance.GetFoundWords()));
            pointsData.Add("Date", DateTimeUtils.DateTimeToISO8601(UnbiasedTime.Instance.UTCNow()));

            GameSparksManager.Instance.SendPoints(points, "LevelComplete", pointsData);
        }

        //

        GameObject completeTextGameObject = GameObjectHelper.GetChildNamedGameObject(_multiplayer ? multiplayerView : pointsView, "CompleteText", true);

        // save game state.
        GameManager.Instance.Player.UpdatePlayerPrefs();

        if (!_multiplayer)
        {
            currentLevel.UpdatePlayerPrefs();
        }

        PreferencesFactory.Save();

        GameObject NameContainer = GameObjectHelper.GetChildNamedGameObject(DialogInstance.Content, "NameContainer", true);
        GameObject LevelName     = GameObjectHelper.GetChildNamedGameObject(DialogInstance.Content, "LevelName", true);
        GameObject Results       = GameObjectHelper.GetChildNamedGameObject(DialogInstance.Content, "Results", true);
        GameObject Buttons       = GameObjectHelper.GetChildNamedGameObject(DialogInstance.Content, "Buttons", true);
        GameObject CloseButton   = GameObjectHelper.GetChildNamedGameObject(DialogInstance.Content, "Close", true);

        GameObject parent = DialogInstance.Content.transform.parent.gameObject;

        Vector3 currentScale = parent.transform.localScale;

        parent.transform.DOScale(new Vector3(0, 0, 0), 0.0f);
        NameContainer.transform.localScale          = new Vector3(0, 0, 0);
        LevelName.transform.localScale              = new Vector3(0, 0, 0);
        Results.transform.localScale                = new Vector3(0, 0, 0);
        Buttons.transform.localScale                = new Vector3(0, 0, 0);
        completeTextGameObject.transform.localScale = new Vector3(0, 0, 0);

        CloseButton.GetComponent <Image>().color = new Color(1, 1, 1, 0);

        //show dialog
        DialogInstance.Show();

        parent.transform.DOScale(currentScale, 1.0f).SetEase(Ease.OutElastic);
        NameContainer.transform.DOScale(new Vector3(1, 1, 1), 1.5f).SetDelay(0.1f).SetEase(Ease.OutElastic);
        LevelName.transform.DOScale(new Vector3(1, 1, 1), 0.8f).SetDelay(0.2f).SetEase(Ease.OutElastic);
        Results.transform.DOScale(new Vector3(1, 1, 1), 0.8f).SetDelay(0.2f).SetEase(Ease.OutElastic);
        Buttons.transform.DOScale(new Vector3(1, 1, 1), 0.8f).SetDelay(0.2f).SetEase(Ease.OutElastic);
        completeTextGameObject.transform.DOScale(new Vector3(1, 1, 1), 0.8f).SetDelay(0.35f).SetEase(Ease.OutElastic);

        CloseButton.GetComponent <Image>().DOFade(1, 0.5f).SetDelay(0.7f);

        GameObject Light = GameObjectHelper.GetChildNamedGameObject(completeTextGameObject, "Light", true);

        Light.transform.DOLocalRotate(new Vector3(0, 0, -360), 10, RotateMode.LocalAxisAdd).SetLoops(-1).SetEase(Ease.Linear);

        //TODO bug - as we increase TimesPlayedForRatingPrompt on both game start (GameManager) and level finish we can miss this comparison.
        if (GameManager.Instance.TimesPlayedForRatingPrompt == TimesPlayedBeforeRatingPrompt)
        {
            GameFeedback gameFeedback = new GameFeedback();
            gameFeedback.GameFeedbackAssumeTheyLikeOptional();
        }

#if UNITY_ANALYTICS
        // record some analytics on the level played
        if (!_multiplayer)
        {
            var values = new Dictionary <string, object>
            {
                { "score", currentLevel.Score },
                { "Coins", coins },
                { "time", time },
                { "level", currentLevel.Number }
            };
            Analytics.CustomEvent("LevelCompleted", values);
        }
#endif

#if UNITY_EDITOR
        if (!_multiplayer)
        {
            GameSparksManager.Instance.SyncProgressCoroutine();
        }
#endif

#if !UNITY_EDITOR
        AdColonyManager.Instance.RequestAd();
        AdColonyManager.Instance.RequestAd(Constants.AdColonyDoubleCoins);

        LoadInterstitialAd();
        LoadAdmobRewarderVideo();
#endif

        // co routine to periodic updates of display (don't need to do this every frame)
        if (!Mathf.Approximately(PeriodicUpdateDelay, 0))
        {
            StartCoroutine(PeriodicUpdate());
        }
    }