Exemplo n.º 1
0
 /// <summary>
 /// Update PlayerPrefs with values that should be saved.
 /// </summary>
 /// Note: This does not call PreferencesFactory.Save()
 /// <param name="prefix"></param>
 /// <param name="useSecurePrefs"></param>
 public void UpdatePlayerPrefs(string prefix = "", bool?useSecurePrefs = null)
 {
     foreach (var variable in BoolVariables)
     {
         if (variable.PersistChanges)
         {
             PreferencesFactory.SetBool(prefix + variable.Tag, variable.Value, useSecurePrefs);
         }
     }
     foreach (var variable in FloatVariables)
     {
         if (variable.PersistChanges)
         {
             PreferencesFactory.SetFloat(prefix + variable.Tag, variable.Value, useSecurePrefs);
         }
     }
     foreach (var variable in IntVariables)
     {
         if (variable.PersistChanges)
         {
             PreferencesFactory.SetInt(prefix + variable.Tag, variable.Value, useSecurePrefs);
         }
     }
     foreach (var variable in StringVariables)
     {
         if (variable.PersistChanges)
         {
             PreferencesFactory.SetString(prefix + variable.Tag, variable.Value, useSecurePrefs);
         }
     }
     foreach (var variable in Vector2Variables)
     {
         if (variable.PersistChanges)
         {
             PreferencesFactory.SetVector2(prefix + variable.Tag, variable.Value, useSecurePrefs);
         }
     }
     foreach (var variable in Vector3Variables)
     {
         if (variable.PersistChanges)
         {
             PreferencesFactory.SetVector3(prefix + variable.Tag, variable.Value, useSecurePrefs);
         }
     }
     foreach (var variable in ColorVariables)
     {
         if (variable.PersistChanges)
         {
             PreferencesFactory.SetColor(prefix + variable.Tag, variable.Value, useSecurePrefs);
         }
     }
 }
Exemplo n.º 2
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();
        }
    public void Play()
    {
        if (ColdStart && PreferencesFactory.GetInt(Constants.KeyNoAds, 0) == 0)
        {
            ColdStart = false;

            if (PreferencesFactory.GetInt(Constants.KeyShowTutorial, 0) == 0)
            {
                PreferencesFactory.SetInt(Constants.KeyShowTutorial, 1);
            }
        }

        NextScene();
    }
Exemplo n.º 4
0
    public void Leaderboard()
    {
        int CountClicks = PreferencesFactory.GetInt(Constants.KeyCountLeaderboardClicks);

        PreferencesFactory.SetInt(Constants.KeyCountLeaderboardClicks, CountClicks + 1);

        //      if (CountClicks > 0 && CountClicks % Constants.ShowAdsPerTime == 0 && Reachability.Instance.IsReachable ()) {
        //	Loading.Instance.Show ();

        //	AdColonyManager.Instance.SetCallback(BannerLeaderboardClosed);
        //	AdColonyManager.Instance.PlayAd(AdColonyManager.Instance.AdForZoneId());
        //} else {
        LeaderboardProcess();
        //}
    }
Exemplo n.º 5
0
    public void Continue()
    {
        // move back Purchase button
        if (_inviteButtonObject != null)
        {
            _inviteButtonObject = null;
            GameObjectUtils.MoveObjectTo(_buttonPurchaseObject, _inviteOriginalParent, _inviteOriginalPosition);
        }

        DialogInstance.DoneFinished();

        if (PreferencesFactory.GetInt(Constants.KeyNoAds, 0) == 1)              // no ads
        {
            ContinueProcess();
            return;
        }

#if UNITY_EDITOR
        ContinueProcess();
        return;
#endif

        int CountClicks = PreferencesFactory.GetInt(Constants.KeyCountNextLevelClicks);
        PreferencesFactory.SetInt(Constants.KeyCountNextLevelClicks, CountClicks + 1);

        Level level = GameManager.Instance.Levels.Selected;

        if (level.Number > 10 && level.Number % Constants.ShowAdsPerTime == 0 && Reachability.Instance.IsReachable())
        {
            int rnd = UnityEngine.Random.Range(1, 10);

            if (rnd < 6 && interstitial != null && interstitial.IsLoaded())
            {
                Loading.Instance.Show();
                interstitial.Show();
                return;
            }

            Loading.Instance.Show();

            AdColonyManager.Instance.SetCallback(BannerClosed);
            AdColonyManager.Instance.PlayAd(AdColonyManager.Instance.AdForZoneId());
        }
        else
        {
            ContinueProcess();
        }
    }
Exemplo n.º 6
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));
        }
    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();
    }
Exemplo n.º 8
0
    public void ToggleNotifications()
    {
        ButtonUtils.PlayClickSound();

        if (PreferencesFactory.GetInt(Constants.KeyNotificationsAllowed, 1) == 1)
        {
            PreferencesFactory.SetInt(Constants.KeyNotificationsAllowed, 0);

            if (!Debug.isDebugBuild)
            {
                Flurry.Flurry.Instance.LogEvent("Notifications_Off");
                Fabric.Answers.Answers.LogCustom("Notifications_Off");
            }

            GameManager.SafeQueueMessage(new UserNotificationsChangedMessage(false));
        }
        else
        {
            PreferencesFactory.SetInt(Constants.KeyNotificationsAllowed, 1);

            if (!LocalNotifications.Allowed())
            {
                LocalNotifications.AllowDialog(() => {
                    PreferencesFactory.SetInt(Constants.KeyNotificationsAllowed, 0);

                    GameObject _n  = GameObjectHelper.GetChildNamedGameObject(gameObject, "Notifications", true);
                    Switch _switch = GameObjectHelper.GetChildComponentOnNamedGameObject <Switch> (_n, "Switch", true);

                    _switch.SetOn(false);
                });
            }
            else
            {
                GameManager.SafeQueueMessage(new UserNotificationsChangedMessage(true));
            }
        }
    }
    void CompleteReward()
    {
        GameObject       animatedCoins = GameObject.Find("AddCoinsAnimated");
        GameObject       addCoinsClone = Instantiate(animatedCoins, animatedCoins.transform.parent);
        AddCoinsAnimated addCoins      = addCoinsClone.GetComponent <AddCoinsAnimated>();

        addCoins.AnimateCoinsAdding(Constants.FreeCoinsDaily);

        //

        PreferencesFactory.SetString(Constants.KeyFreeCoinsAvailable, UnbiasedTime.Instance.Now().AddMinutes(Constants.MinutesBetweenFreeCoins).ToString(CultureInfo.InvariantCulture));

        int TimesFreeCoins = PreferencesFactory.GetInt(Constants.KeyFreeCoinsCounter, 0);

        TimesFreeCoins += 1;

        PreferencesFactory.SetInt(Constants.KeyFreeCoinsCounter, TimesFreeCoins);

        if (TimesFreeCoins >= Constants.TimesFreeCoins)
        {
            GameObjectHelper.SafeSetActive(FreeCoinsObject, false);
            GameObjectHelper.SafeSetActive(FreeCoinsCounterObject, true);
        }
    }
Exemplo n.º 10
0
    public static bool InviteBonusCoins()
    {
        DateTime dateTime = DateTime.Parse(PreferencesFactory.GetString(Constants.KeyInviteLastDate, UnbiasedTime.Instance.Now().AddDays(-1).ToString(CultureInfo.InvariantCulture)));

        if (dateTime.Date < UnbiasedTime.Instance.Now().Date)
        { // last invite was yesterday, reset all data
            PreferencesFactory.SetString(Constants.KeyInviteLastDate, UnbiasedTime.Instance.Now().ToString(CultureInfo.InvariantCulture));
            PreferencesFactory.SetInt(Constants.KeyInvitesTotal, 0);

            dateTime = UnbiasedTime.Instance.Now();
        }

        bool addedCoins = false;

        int totalInvites = PreferencesFactory.GetInt(Constants.KeyInvitesTotal);

#if UNITY_EDITOR
        totalInvites = 0;
#endif

        if (dateTime.Date == UnbiasedTime.Instance.Now().Date&& totalInvites < Constants.InviteMaxPerDay)
        {
            GameObject animatedCoins = GameObject.Find("AddCoinsAnimated");

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

            addCoins.AnimateCoinsAdding(Constants.InviteAwardCoins);

            addedCoins = true;
        }

        PreferencesFactory.SetInt(Constants.KeyInvitesTotal, totalInvites + 1);

        return(addedCoins);
    }
Exemplo n.º 11
0
    public override void ClickUnlocked()
    {
        if (PreferencesFactory.GetInt(Constants.KeyNoAds, 0) == 1)
        { // no ads
            ClickUnlockedProcess();
            return;
        }

        int CountSelectLevelClicks = PreferencesFactory.GetInt(Constants.KeyCountSelectLevelClicks);

        PreferencesFactory.SetInt(Constants.KeyCountSelectLevelClicks, CountSelectLevelClicks + 1);

        //if (CountSelectLevelClicks > 0 && CountSelectLevelClicks % Constants.ShowAdsPerTime == 0 && Reachability.Instance.IsReachable())
        //{
        //    Loading.Instance.Show();

        //    AdColonyManager.Instance.SetCallback(BannerUnlockedClosed);
        //    AdColonyManager.Instance.PlayAd(AdColonyManager.Instance.AdForZoneId());
        //}
        //else
        //{
        ClickUnlockedProcess();
        //}
    }
Exemplo n.º 12
0
 public void MainMenu()
 {
     PreferencesFactory.SetInt(Constants.KeyShowBannerOnMainMenuScreen, 1);
     GameManager.LoadSceneWithTransitions("Menu");
 }
    public void SendPoints(int points, string source = null, JSONObject pointsJsonData = null)
    {
        int    offlinePoints     = PreferencesFactory.GetInt(Constants.KeyOfflinePoints, 0);
        string _pointsDataString = PreferencesFactory.GetString(Constants.KeyOfflinePointsData, null);

        if (pointsJsonData != null && source != null)
        {
            pointsJsonData.Add("source", source);
        }

        JSONArray _pointsData = new JSONArray();

        if (!string.IsNullOrEmpty(_pointsDataString))
        {
            try
            {
                _pointsData = JSONArray.Parse(_pointsDataString);
            } catch (Exception e) {}
        }

        if (pointsJsonData != null)     // add new record
        {
            _pointsData.Add(pointsJsonData);
        }

        if (Reachability.Instance.IsReachable() == false || IsUserLoggedIn() == false)
        {
            PreferencesFactory.SetInt(Constants.KeyOfflinePoints, points + offlinePoints);
            PreferencesFactory.SetString(Constants.KeyOfflinePointsData, _pointsData.ToString());

            return;
        }

        if (points + offlinePoints <= 0)
        {
            return;
        }

        int levelNumber = -1;

        try
        {
            Level level = LevelController.FirstUnplayedLevel();

            if (level != null)
            {
                levelNumber = level.Number - 1;
            }
        } catch (Exception e) {}

        GSRequestData requestData = new GSRequestData();

        requestData.AddNumber("offlinePoints", offlinePoints);
        requestData.AddNumber("score", points);
        requestData.AddNumber("lastPlayedLevel", levelNumber);

        if (_pointsData != null)
        {
            requestData.AddJSONStringAsObject("pointsData", _pointsData.ToString());
        }

        if (source != null)
        {
            requestData.AddString("source", source);
        }

        new LogEventRequest()
        .SetEventKey("SubmitScoreV2")
        .SetEventAttribute("score", points + offlinePoints)
        .SetEventAttribute("data", requestData)
        .Send((response) => {
            if (!response.HasErrors)
            {
                PreferencesFactory.DeleteKey(Constants.KeyOfflinePoints);
                PreferencesFactory.DeleteKey(Constants.KeyOfflinePointsData);
            }
        });
    }
Exemplo n.º 14
0
    /// <summary>
    /// Show a free prize dialog that gives the user coins. We default to the standard General Message window, adding any additional
    /// content as setup in the FreePrizeManager configuration.
    /// </summary>
    public DialogInstance ShowFreePrizeDialog(Action <DialogInstance> doneCallback = null)
    {
        // only allow the free prize dialog to be shown once.
        if (IsShowingFreePrizeDialog)
        {
            return(null);
        }

        IsShowingFreePrizeDialog = true;
        _prizeIsProcessed        = false;
        dialogInstance           = DialogManager.Instance.Create(ContentPrefab, null, null, null,
                                                                 runtimeAnimatorController: ContentAnimatorController);

        Sprite sprite = null;
        string text   = BonusText();

        if (prizeIsCoins && this.PrizeItems > 0)
        {
            sprite = Resources.Load <Sprite>("Images/coins");
        }

        string   DateLastFreePrizeTakeString = PreferencesFactory.GetString(Constants.KeyDateLastFreePrizeTake);
        DateTime DateLastFreePrizeTake       = UnbiasedTime.Instance.Now();

        if (!DateLastFreePrizeTakeString.Equals(""))
        {
            DateLastFreePrizeTake = DateTime.Parse(DateLastFreePrizeTakeString);
        }

        int DaysInRow = PreferencesFactory.GetInt(Constants.KeyFreePrizeTakeDaysInRow, 1);

        if (DateLastFreePrizeTake.AddDays(1).Date == UnbiasedTime.Instance.Now().Date)
        {
            DaysInRow += 1;
            PreferencesFactory.SetInt(Constants.KeyFreePrizeTakeDaysInRow, DaysInRow);
        }
        else
        { // reset
            DaysInRow = 1;
            PreferencesFactory.SetInt(Constants.KeyFreePrizeTakeDaysInRow, DaysInRow);
        }

        GameObject Days = GameObjectHelper.GetChildNamedGameObject(dialogInstance.gameObject, "Days", true);

        for (int i = 0; i < Constants.DailyBonusItems.Length; i++)
        {
            int prizeValue = Constants.DailyBonusItems[i];

            string     dayText = string.Format("Day{0}", (i + 1));
            GameObject day     = GameObjectHelper.GetChildNamedGameObject(Days, dayText, true);

            if (!day)
            {
                continue;
            }

            Text t = GameObjectHelper.GetChildNamedGameObject(day, "Text", true).GetComponent <Text>();
            t.text = prizeValue.ToString();

            if (DaysInRow - 1 > i)
            {
                GameObject image = GameObjectHelper.GetChildNamedGameObject(day, "Image", true);
                GameObjectHelper.SafeSetActive(image, true);
            }

            //			if ( DaysInRow-1 == i) {
            //				GameObject today = GameObjectHelper.GetChildNamedGameObject(day, "Today", true);
            //				GameObjectHelper.SafeSetActive (today, true);
            //
            //				GameObject dayNumber = GameObjectHelper.GetChildNamedGameObject(day, "DayNumber", true);
            //				GameObjectHelper.SafeSetActive (dayNumber, false);
            //			}

            if (DaysInRow == (i + 1))
            { // add daily bonus
                this.PrizeItems += prizeValue;

                GameObject claimButton = GameObjectHelper.GetChildNamedGameObject(dialogInstance.Content, "ClaimButton", true);

                Text claimText = GameObjectHelper.GetChildComponentOnNamedGameObject <Text>(claimButton, "Text", true);

                if (prizeIsPoints)
                {
                    claimText.text = LocaliseText.Format("FreePrize.ClaimPoints", this.PrizeItems);
                }

                if (prizeIsCoins)
                {
                    claimText.text = LocaliseText.Format("FreePrize.ClaimButton", this.PrizeItems);
                }
            }
        }

        dialogInstance.Show(title: LocaliseText.Get("FreePrize.Title"), text: text, text2Key: "FreePrize.Text2",
                            doneCallback: (DialogInstance _dialogInstance) => {
            if (doneCallback != null)
            {
                doneCallback(_dialogInstance);
            }

            ShowFreePrizeDone(_dialogInstance);
        },
                            dialogButtons:
                            ContentShowsButtons
            ? DialogInstance.DialogButtonsType.Custom
            : DialogInstance.DialogButtonsType.Ok);

        GameObject ImageCoins = GameObjectHelper.GetChildNamedGameObject(dialogInstance.gameObject, "ph_Image", true);

        ImageCoins.SetActive(false);

        if (this.PrizeItems > 0 && prizeIsCoins && sprite != null)
        {
            ImageCoins.SetActive(true);
            ImageCoins.GetComponent <Image>().sprite = sprite;
        }

        StartNewCountdown();

        if (!Debug.isDebugBuild)
        {
            Fabric.Answers.Answers.LogContentView("FreePrize", "Dialog");
        }
#if !UNITY_EDITOR
        AdColonyManager.Instance.RequestAd(Constants.AdColonyDoubleDailyBonus);
        LoadAdmobRewarderVideo();
#endif

        return(dialogInstance);
    }
    // Use this for initialization
    void Start()
    {
        Branch.initSession(CallbackWithBranchUniversalObject);

        int show = PreferencesFactory.GetInt(Constants.KeyShowBannerOnMainMenuScreen, 0);

        container = GameObject.Find("Container");

        if (PreferencesFactory.GetInt(Constants.KeyNoAds, 0) == 1)
        {
            show = 0; // disable ads
        }

        _rewardShareButton = GameObjectHelper.GetChildNamedGameObject(gameObject, "RewardButton", true);

        if (_rewardShareButton != null && RewardsShareHelper.WillReward())
        {
            ShowRewardShareButton();
        }

        #if !UNITY_EDITOR
        // delay request until AdColony is configured
        StartCoroutine(CoRoutines.DelayedCallback(1.5f, () =>
        {
            AdColonyManager.Instance.RequestAd();
        }));
        #endif

        if (show > 0)             // show banner only when return to main screen, not cold start
        {
            AddBanner();
            PreferencesFactory.DeleteKey(Constants.KeyShowBannerOnMainMenuScreen);

            int CountClicks = PreferencesFactory.GetInt(Constants.KeyCountMainMenuClicks);
            PreferencesFactory.SetInt(Constants.KeyCountMainMenuClicks, CountClicks + 1);

            //         if (CountClicks > 0 && CountClicks % Constants.ShowAdsPerTime == 0 && Reachability.Instance.IsReachable ()) {
            //	Loading.Instance.Show ();

            //	AdColonyManager.Instance.SetCallback (BannerMainMenuClosed);
            //             AdColonyManager.Instance.PlayAd(AdColonyManager.Instance.AdForZoneId());
            //}
        }
        else             // show banner on cold start
        {
            ColdStart = true;

            int CountMainMenuColdStart = PreferencesFactory.GetInt(Constants.KeyCountMainMenuColdStart);
            PreferencesFactory.SetInt(Constants.KeyCountMainMenuColdStart, CountMainMenuColdStart + 1);
        }

        GameManager.SafeAddListener <BannerLoadedMessage> (BannerLoadedHandler);
        GameManager.SafeAddListener <VideoAdShowingMessage> (VideoAdShowingHandler);

        ((CustomGameManager)GameManager.Instance).ResetDefaultSound();

        if (!Debug.isDebugBuild)
        {
            FlurryIOS.LogPageView();
            FlurryAndroid.OnPageView();

            Fabric.Answers.Answers.LogContentView("Menu", "Screen");
        }

        StartCoroutine(CoRoutines.DelayedCallback(0.5f, () =>
        {
            CheckForPrize();
        }));

        GameSparksManager.Instance.SetGameMode(GameMode.Single);

        AnimatePig();
    }
    protected override void GameSetup()
    {
        // secure preferences
        PreferencesFactory.UseSecurePrefs = SecurePreferences;
        if (SecurePreferences)
        {
            if (string.IsNullOrEmpty(PreferencesPassPhrase))
            {
                Debug.LogWarning("You have not set a custom pass phrase in GameManager | Player Preferences. Please correct for improved security.");
            }
            else
            {
                PreferencesFactory.PassPhrase = PreferencesPassPhrase;
            }
            PreferencesFactory.AutoConvertUnsecurePrefs = AutoConvertUnsecurePrefs;
        }

        StartupLevels = NumberOfAutoCreatedLevels;

        int NumberOfAdditionalCreatedLevels = PreferencesFactory.GetInt(Constants.KeyNumberOfAdditionalCreatedLevels);

        NumberOfAutoCreatedLevels += NumberOfAdditionalCreatedLevels;

        string FirstAppStartDate = PreferencesFactory.GetString(Constants.KeyFirstAppStartDate, null);

        if (FirstAppStartDate == null)
        {
            PreferencesFactory.SetString(Constants.KeyFirstAppStartDate, UnbiasedTime.Instance.Now().ToString(CultureInfo.InvariantCulture));
        }

        PreferencesFactory.SetString(Constants.KeyLastAppStartDate, UnbiasedTime.Instance.Now().ToString(CultureInfo.InvariantCulture));

        int TimesAppStarted = PreferencesFactory.GetInt(Constants.KeyTimesAppStarted, 0);

        PreferencesFactory.SetInt(Constants.KeyTimesAppStarted, TimesAppStarted + 1);

        base.GameSetup();

        if (PlayerPrefs.GetInt("ManualChangedLanguage", 0) == 0)
        {
#if UNITY_ANDROID || UNITY_EDITOR
            string savedLanguage  = PreferencesFactory.GetString("Language", useSecurePrefs: false);
            string systemLanguage = DeviceLanguage();

            // user does not changed his language manual
            // and system language is different from previous auto-detected
            if (systemLanguage != savedLanguage)
            {
                LanguageController.ChangeLanguage(systemLanguage);
            }
#endif

#if UNITY_IOS
            IOSNativeUtility.OnLocaleLoaded += GetLocale;
            IOSNativeUtility.Instance.GetLocale();
#endif
        }

        Packs = new PackGameItemManager();

        if (LevelSetupMode == GameItemSetupMode.FromResources)
        {
            Packs.Load(1, NumberOfAutoCreatedPacks);
        }

        Ranks = new RankGameItemManager();

        if (LevelSetupMode == GameItemSetupMode.FromResources)
        {
            Ranks.Load(1, NumberOfAutoCreatedRanks);
        }

        Rank rank = Ranks.GetItem(1);

        if (!rank.IsUnlocked)
        {
            rank.IsUnlocked = true; // first rank is unlocked by default
            rank.UpdatePlayerPrefs();
        }

        Pack pack = Packs.GetItem(1);

        if (!pack.IsUnlocked)
        {
            pack.IsUnlocked = true; // first pack is unlocked by default
            pack.UpdatePlayerPrefs();
        }

        Level level = Levels.GetItem(1);

        if (!level.IsUnlocked)
        {
            level.IsUnlocked = true; // first level is unlocked by default
            level.UpdatePlayerPrefs();
        }

        GameManager.SafeAddListener <UserNotificationsChangedMessage>(UserNotificationsChangedHandler);
        GameManager.SafeAddListener <LocalisationChangedMessage>(LocalisationHandler);

        // bug fix in gameframework when user loose all his lives and start game again and Lives back to full
        if (FirstAppStartDate != null)
        { // but only after first start ever
            Player.Lives = Player.GetSettingInt("Lives", 0);
        }

        if (FirstAppStartDate == null)
        { // first start
            PreferencesFactory.SetInt(Constants.KeyNotificationsAllowed, 1);
        }

        //

        Advertisement.Initialize(Constants.UnityAdsGameId);

        if (BackGroundAudioVolume > Constants.DefaultAudioVolume)
        {
            BackGroundAudioVolume = Constants.DefaultAudioVolume;
        }

        if (EffectAudioVolume > Constants.DefaultAudioVolume)
        {
            EffectAudioVolume = Constants.DefaultAudioVolume;
        }

        _currentBackgroundSoundVolume = BackGroundAudioVolume;

        if (!SoundEnabled())
        {
            BackGroundAudioSource.Stop();
        }

#if UNITY_IPHONE
        SA.IOSNative.Core.AppController.Subscribe();

        SA.IOSNative.Core.AppController.OnApplicationDidReceiveMemoryWarning += OnApplicationDidReceiveMemoryWarning;
#endif

#if !UNITY_EDITOR
        CancelLocalNotifications();
        RegisterLocalNotifications();
#endif
    }
Exemplo n.º 17
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);
    }
Exemplo n.º 18
0
    void Start()
    {
        GameManager.SafeAddListener <FacebookProfilePictureMessage>(FacebookProfilePictureHandler);

        _avatarImage   = GameObjectHelper.GetChildComponentOnNamedGameObject <RawImage> (gameObject, "AvatarImage");
        _userNameField = GameObjectHelper.GetChildComponentOnNamedGameObject <InputField> (gameObject, "UsernameField", true);

        _userNameField.text = PreferencesFactory.GetString(Constants.ProfileUsername);

        _statsContainer = GameObjectHelper.GetChildNamedGameObject(gameObject, "Stats", true);

                #if UNITY_IOS
        IOSCamera.OnImagePicked += OnImage;
                #endif

                #if UNITY_ANDROID
        AndroidCamera.Instance.OnImagePicked += OnImage;
                #endif

        string avatarId = PreferencesFactory.GetString(Constants.ProfileAvatarUploadId);

        if (avatarId != null)
        {
            GameSparksManager.Instance.DownloadAvatar(avatarId, (Texture2D image) => {
                if (_avatarImage != null && image != null)
                {
                    _avatarImage.texture = image;
                }
            });
        }
        else if (PreferencesFactory.HasKey(Constants.ProfileFBUserId))
        {
            FacebookRequests.Instance.LoadProfileImages(PreferencesFactory.GetString(Constants.ProfileFBUserId));
        }

        GameSparksManager.Instance.LeaderboardRating((int rating) => {
            PreferencesFactory.SetInt(Constants.ProfileRating, rating);
            SetRating(rating);
        });

        GameSparksManager.Instance.UserStats((GSData data) => {
            if (data.GetGSData("Novice") != null)
            {
                GSData rank = data.GetGSData("Novice");
                StatsAddRow("Novice", (int)rank.GetInt("wins"), (int)rank.GetInt("lose"), (int)rank.GetInt("draw"));
            }

            if (data.GetGSData("Advanced") != null)
            {
                GSData rank = data.GetGSData("Advanced");
                StatsAddRow("Advanced", (int)rank.GetInt("wins"), (int)rank.GetInt("lose"), (int)rank.GetInt("draw"));
            }

            if (data.GetGSData("Master") != null)
            {
                GSData rank = data.GetGSData("Master");
                StatsAddRow("Master", (int)rank.GetInt("wins"), (int)rank.GetInt("lose"), (int)rank.GetInt("draw"));
            }

            if (data.GetGSData("Professional") != null)
            {
                GSData rank = data.GetGSData("Professional");
                StatsAddRow("Professional", (int)rank.GetInt("wins"), (int)rank.GetInt("lose"), (int)rank.GetInt("draw"));
            }
        });

        SetRating(PreferencesFactory.GetInt(Constants.ProfileRating, 0));
    }
Exemplo n.º 19
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();
    }