//============================================================================= void SetupNewsFlash(string InputText) { JSON Decoder = new JSON(); Decoder.serialized = InputText; JSON NewsDataJSON = Decoder.ToJSON("newsData"); int PopupVersion = NewsDataJSON.ToInt("version"); int LiveDataVersion = NewsDataJSON.ToInt("liveDataVersion"); int CouponCodesActive = NewsDataJSON.ToInt("couponCodesActive"); PlayerPrefs.SetInt("couponCodesActive", CouponCodesActive); // Do we need to download live data? if (LiveDataVersion > PlayerPrefs.GetInt("LiveDataVersion", PreHelpers.GetLiveDataVersion())) { Debug.Log("Updating live data!"); //PlayerPrefsWrapper.SetInt( "LiveDataVersion" , LiveDataVersion ); StartCoroutine(GetLiveData(LiveDataVersion, NewsDataJSON.ToString("liveDataURL"))); } else { Debug.Log("Don't need to update live data - our version:" + PlayerPrefs.GetInt("LiveDataVersion", PreHelpers.GetLiveDataVersion()) + " remote version:" + LiveDataVersion); } }
//===================================================== void Start() { // Unpack any live data updates present in the local files folder LoadLiveUpdate(); // Set opening scene language switch (PreHelpers.GetLanguageCode()) { default: m_SceneSettingEN.SetActive(true); break; case "it": m_SceneSettingIT.SetActive(true); break; case "ru": m_SceneSettingRU.SetActive(true); break; case "de": m_SceneSettingDE.SetActive(true); break; } ScreenManager.FadeInCompleteEvent += OnFadeInCompleteEvent; ScreenManager.FadeOutCompleteEvent += OnFadeOutCompleteEvent; ScreenManager.FadeIn(); }
//===================================================== //void OnApplicationFocus( bool focusStatus ) // { //#if UNITY_ANDROID // // Only apply on pause event when app loses focus e.g. device home-button press // if( focusStatus == true ) // PauseGame( focusStatus ); //#endif // } //===================================================== private IEnumerator CheckForNewDay() { while (true) { Debug.Log("Check for new day"); if (PreHelpers.CheckForNewDay() == true) { GameDataManager.Instance.ResetForNewDay(true); } // Repeat check every hour yield return(new WaitForSeconds(3600.0f)); } }
//===================================================== private void RegisterWithColliders() { var children = PreHelpers.GetAllChildren(_thisTransform); foreach (var child in children) { if (child.tag == UnityTags.ColliderCanDamage) { var script = child.GetComponent <ColliderObstacle>(); if (script != null) { script.Init(this); } } } }
//===================================================== public void OnBossDeadEvent() { _isPlayerDead = false; if (BossManager.Instance == null || BossManager.Instance.CutsceneBossLoses == null) { return; } _isLeavingBossRoom = true; SetNextLocation(eLocation.MAIN_HALL); // Play cutscene if (BossLosesEvent != null) { BossLosesEvent(BossManager.Instance.CutsceneBossLoses); } // Apply wild magic bonus if (PlayerPrefsWrapper.HasKey("FirstBossKill") == false || PlayerPrefsWrapper.GetInt("FirstBossKill") != 1) { PlayerPrefsWrapper.SetInt("FirstBossKill", 1); GameDataManager.Instance.AddWildMagicAndPopulation( WildMagicItemsManager.GetWildMagicItem("WM_RATE_BOSS_FIGHT_WIN_FIRST")); } else { GameDataManager.Instance.AddWildMagicAndPopulation( WildMagicItemsManager.GetWildMagicItem("WM_RATE_BOSS_FIGHT_WIN_DEFAULT")); } // Increment boss level if (GameDataManager.Instance.PlayerBossLevel < GameDataManager.Instance.PlayerMaxFairyLevel) { GameDataManager.Instance.PlayerBossLevel += 1; } // If boss is at level 3 then start timer intervals between boss appearances // Note: time-interval-start checked by boss door on entering MainHall scene if (GameDataManager.Instance.PlayerBossLevel >= GameDataManager.Instance.PlayerMaxFairyLevel) { PlayerPrefsWrapper.SetDouble("BossRoomTimedIntervalStarted", PreHelpers.UnixUtcNow()); } }
//===================================================== void Update() { UpdateTransition(Time.deltaTime); // Update card zoom if (m_bInTransition == false) { if (m_bCardZoomed) { PreHelpers.DeltaTend(ref m_CurCardZoom, 2.0f, 8.0f, Time.deltaTime); } else { PreHelpers.DeltaTend(ref m_CurCardZoom, 1.0f, 8.0f, Time.deltaTime); } m_sprCardFrame.gameObject.transform.localScale = new Vector3(m_CurCardZoom, m_CurCardZoom, 1.0f); } }
//============================================================================= public void ReportScoreTest(System.Int64 Score, string PlayerName, string PlayerID) { #if UNITY_EDITOR string sourceType = "Editor"; #elif UNITY_IPHONE string sourceType = "iOS"; #elif UNITY_ANDROID string sourceType = "iOS"; //"Android"; #else string sourceType = "Unknown"; #endif string CurCountry = PreHelpers.GetCountryCode(); PlayerScore NewScore = new PlayerScore { playername = PlayerName, playerid = PlayerID, points = Score, table = "testboard", allowduplicates = false, source = sourceType, fields = new PDictionary { { "country", CurCountry } }, filters = new PDictionary { { "perpage", 5 }, { "highest", true }, { "mode", eScoreTime.AllTime.ToString().ToLower() }, { "allowduplicates", false } } }; Playtomic.Leaderboards.SaveAndList(NewScore, ScoreListComplete); }
//============================================================================= private static bool LoadItemsList() { if (isItemListLoaded) { return(true); } isItemListLoaded = true; StringReader reader = null; if (PlayerPrefs.HasKey(PreHelpers.GetLiveDataVersionString()) && false) { // Load locally string DocPath = PreHelpers.GetFileFolderPath(); string FilePath = DocPath + "Fairies.txt"; // Read file string Contents = null; try { StreamReader CurFile = new StreamReader(FilePath); Contents = CurFile.ReadToEnd(); // Close file CurFile.Close(); } catch { PlayerPrefsWrapper.DeleteKey(PreHelpers.GetLiveDataVersionString()); } reader = new StringReader(Contents); } else { // Load from resources string fullpath = "Fairies/Fairies"; TextAsset textAsset = (TextAsset)Resources.Load(fullpath, typeof(TextAsset)); if (textAsset == null) { Debug.Log(fullpath + " file not found."); return(false); } reader = new StringReader(textAsset.text); } // Create the fairies item list if one doesn't exist if (null == itemList) { itemList = new List <FairyItemData>(64); } // Clear the dictionary itemList.Clear(); string dataVal = string.Empty; string intext = string.Empty; // [ Fairy | Unlock Cost | Level 1 Cost | Level 2 Cost | Level 3 Cost ] int maxColumns = 5; int columnCount = 0; int itemCount = 0; // First parse through rows until we find the starting one // The 'fairies.txt' file has loads of info at the start that we can ignore as it's all excel settings int RowCount = 0; while (true) { intext = reader.ReadLine(); int Idx = intext.IndexOf("<Row"); if (Idx != -1) { RowCount++; } if (RowCount == 6) { break; } } // Start of text data, begin parsing the rows while (true) { int Idx, Idx2, Idx3, Idx4; bool isIdValid = false; columnCount = 0; // Read cell containing text code intext = reader.ReadLine(); // intext might look something like this now: // <Cell ss:StyleID="s32"><Data ss:Type="String">0001</Data></Cell> // Find the data in the cell - in this case it's "Item ID" Idx4 = intext.IndexOf("><"); if (Idx4 != -1) { Idx2 = intext.IndexOf(">", Idx4 + 2); if (Idx2 != -1) { Idx3 = intext.IndexOf("<", Idx2); if (Idx3 != -1) { // String is between Idx2 and Idx3 - this is the text 'ItemId' - "0001" dataVal = intext.Substring(Idx2 + 1, Idx3 - Idx2 - 1); itemList.Add(new FairyItemData()); UpdateItemData(itemCount, columnCount, dataVal); isIdValid = true; } } ++columnCount; } // If we've found an itemId continue reading the item data for this item if (isIdValid) { while (columnCount < maxColumns) { // Read cell containing text code intext = reader.ReadLine(); Idx4 = intext.IndexOf("><"); if (Idx4 != -1) { Idx2 = intext.IndexOf(">", Idx4 + 2); if (Idx2 != -1) { Idx3 = intext.IndexOf("<", Idx2); if (Idx3 != -1) { // String is between Idx2 and Idx3 - this is the text 'ItemId' - "0001" dataVal = intext.Substring(Idx2 + 1, Idx3 - Idx2 - 1); UpdateItemData(itemCount, columnCount, dataVal); } } } ++columnCount; } ++itemCount; } // Find the end of this row by looking for the start of the next row while (true) { intext = reader.ReadLine(); Idx = intext.IndexOf("<Row"); if (Idx != -1) { // Found end of row break; } else { Idx = intext.IndexOf("Table>"); if (Idx != -1) { // Found end of table //Debug.Log("Finished loading fairies items data list."); reader.Dispose(); // Order list by priority //itemList.Sort((x,y) => x.GetOrderPriority() - y.GetOrderPriority()); return(true); } } } } }
//===================================================== public void Update() { if (m_bSwiping) { Vector3 WorldPos = m_GUI2DCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1.0f)); WorldPos *= 800.0f; float SwipingDeltaX = WorldPos.x - m_SwipingStartX; m_SwipingAccel = (WorldPos - m_LastWorldPos[3]).x; for (int MIdx = 3; MIdx > 0; MIdx--) { m_LastWorldPos[MIdx] = m_LastWorldPos[MIdx - 1]; } m_LastWorldPos[0] = WorldPos; m_DestinationItemIndex = m_SwipingStartItemIndex - (SwipingDeltaX * 0.0079f); List <ClothingItemData> CurClothingList = ClothingItemsManager.GetClothingItems(m_CurrentFairy); int MaxItems = CurClothingList.Count; float MinSwipePos = (float)-2.0f; float MaxSwipePos = (float)(MaxItems - 4); if (MaxSwipePos < 0.0f) { MaxSwipePos = 0.0f; } //MinSwipePos -= 0.4f; MaxSwipePos += 0.4f; if (m_DestinationItemIndex < MinSwipePos) { m_DestinationItemIndex = MinSwipePos; } if (m_DestinationItemIndex > MaxSwipePos) { m_DestinationItemIndex = MaxSwipePos; } if (Input.GetMouseButtonUp(0)) { m_bSwiping = false; //m_DestinationItemIndex = (float)((int)(m_DestinationItemIndex + 0.5f)); m_SwipingAccel = Mathf.Clamp(m_SwipingAccel, -25.0f, 25.0f); } } else { // Not swiping Vector3 WorldPos = m_GUI2DCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1.0f)); WorldPos *= 800.0f; for (int MIdx = 3; MIdx > 0; MIdx--) { m_LastWorldPos[MIdx] = WorldPos; } m_SwipingStartX = WorldPos.x; m_SwipingStartItemIndex = m_DestinationItemIndex; //Debug.Log( WorldPos ); if (Input.GetMouseButtonDown(0)) { if ((WorldPos.y > 1004.0f) && (WorldPos.y < 1345.0f)) { if ((WorldPos.x > -497.0f) && (WorldPos.x < 314.0f)) { m_bSwiping = true; m_SwipingAccel = 0.0f; } } } else { //m_DestinationItemIndex -= m_SwipingAccel * Time.deltaTime * 0.35f; m_SwipingAccel *= 0.92f; } } PreHelpers.DeltaTend(ref m_CurrentItemIndex, m_DestinationItemIndex, 7.5f, Time.deltaTime); // Update renderer if (RackRenderer.instance != null) { RackRenderer.instance.m_CurItem = m_CurrentItemIndex; } }
//============================================================================= private static bool LoadItemsList() { if (isItemListLoaded) { return(true); } isItemListLoaded = true; StringReader reader = null; if (PlayerPrefs.HasKey(PreHelpers.GetLiveDataVersionString()) && false) { // Load locally string DocPath = PreHelpers.GetFileFolderPath(); string FilePath = DocPath + "Cards.txt"; // Read file string Contents = null; try { StreamReader CurFile = new StreamReader(FilePath); Contents = CurFile.ReadToEnd(); // Close file CurFile.Close(); } catch { PlayerPrefsWrapper.DeleteKey(PreHelpers.GetLiveDataVersionString()); } reader = new StringReader(Contents); } else { // Load from resources string fullpath = "Cards/Cards"; TextAsset textAsset = (TextAsset)Resources.Load(fullpath, typeof(TextAsset)); if (textAsset == null) { Debug.Log(fullpath + " file not found."); return(false); } reader = new StringReader(textAsset.text); } // Create the TradingCard item list if one doesn't exist if (null == itemList) { itemList = new List <TradingCardSpreadsheetItem>(64); } // Clear the dictionary itemList.Clear(); string dataVal = string.Empty; string intext = string.Empty; // [ ItemID | Classification | Value | ValueScuffed | Rarity | Wait Time | Reveal Price | Page | Position | SmallGUI - 2D | LargeGUI - 2D ] int maxColumns = 11; int columnCount = 0; int itemCount = 0; // First parse through rows until we find the starting one // The 'TradingCarditems.txt' file has loads of info at the start that we can ignore as it's all excel settings int RowCount = 0; while (true) { intext = reader.ReadLine(); int Idx = intext.IndexOf("<Row"); if (Idx != -1) { RowCount++; } if (RowCount == 6) { break; } } // Start of text data, begin parsing the rows while (true) { int Idx, Idx2, Idx3, Idx4; bool isIdValid = false; columnCount = 0; // Read cell containing text code intext = reader.ReadLine(); // intext might look something like this now: // <Cell ss:StyleID="s32"><Data ss:Type="String">0001</Data></Cell> // Find the data in the cell - in this case it's "Item ID" Idx4 = intext.IndexOf("><"); if (Idx4 != -1) { Idx2 = intext.IndexOf(">", Idx4 + 2); if (Idx2 != -1) { Idx3 = intext.IndexOf("<", Idx2); if (Idx3 != -1) { // String is between Idx2 and Idx3 - this is the text 'ItemId' - "0001" dataVal = intext.Substring(Idx2 + 1, Idx3 - Idx2 - 1); itemList.Add(new TradingCardSpreadsheetItem()); UpdateItemData(itemCount, columnCount, dataVal); isIdValid = true; } } ++columnCount; } // If we've found an itemId continue reading the item data for this item if (isIdValid) { while (columnCount < maxColumns) { // Read cell containing text code intext = reader.ReadLine(); Idx4 = intext.IndexOf("><"); if (Idx4 != -1) { Idx2 = intext.IndexOf(">", Idx4 + 2); if (Idx2 != -1) { Idx3 = intext.IndexOf("<", Idx2); if (Idx3 != -1) { // String is between Idx2 and Idx3 - this is the text 'ItemId' - "0001" dataVal = intext.Substring(Idx2 + 1, Idx3 - Idx2 - 1); UpdateItemData(itemCount, columnCount, dataVal); } } } ++columnCount; } ++itemCount; } // Find the end of this row by looking for the start of the next row while (true) { intext = reader.ReadLine(); Idx = intext.IndexOf("<Row"); if (Idx != -1) { // Found end of row break; } else { Idx = intext.IndexOf("Table>"); if (Idx != -1) { // Found end of table //Debug.Log("Finished loading TradingCard items data list."); reader.Dispose(); // Order list by priority //itemList.Sort((x,y) => x.GetOrderPriority() - y.GetOrderPriority()); // Expand each item type into individual page sections int NumWinxPages = GetPageCount(eTradingCardClassification.WINX); int NumWildPages = GetPageCount(eTradingCardClassification.WILD); int NumStoryPages = GetPageCount(eTradingCardClassification.STORY); int NumStandardPages = GetPageCount(eTradingCardClassification.STANDARD); pageTypeOffsets[(int)eTradingCardClassification.WINX] = 0; pageTypeOffsets[(int)eTradingCardClassification.WILD] = NumWinxPages; pageTypeOffsets[(int)eTradingCardClassification.STORY] = NumWinxPages + NumWildPages; pageTypeOffsets[(int)eTradingCardClassification.STANDARD] = NumWinxPages + NumWildPages + NumStoryPages; OffsetPageCount(eTradingCardClassification.WINX, pageTypeOffsets[(int)eTradingCardClassification.WINX]); OffsetPageCount(eTradingCardClassification.WILD, pageTypeOffsets[(int)eTradingCardClassification.WILD]); OffsetPageCount(eTradingCardClassification.STORY, pageTypeOffsets[(int)eTradingCardClassification.STORY]); OffsetPageCount(eTradingCardClassification.STANDARD, pageTypeOffsets[(int)eTradingCardClassification.STANDARD]); return(true); } } } } }
//===================================================== void Start() { if (Application.isPlaying == false) { return; } // Boss Doors - enable boss torches - all torches enabled unlocks boss door if (_type != eDoorType.BOSS || _targetScene != eLocation.BOSS_ROOM || _bossTorches == null) { return; } // Max level for fairies and boss var maxLevel = GameDataManager.Instance.PlayerMaxFairyLevel; // Get current boss level var bossLevel = GameDataManager.Instance.PlayerBossLevel; // Get current min fairy level for boss fight var minFairyLevel = GameDataManager.Instance.PlayerFairyMinLevel(); // Are we at the max-level boss? If so, check time interval else check current fairy levels // Note: time-interval-start set after killing level 3 boss: GameManager->OnBossDeadEvent() if (bossLevel >= maxLevel && minFairyLevel >= maxLevel) { // Get time in seconds since last boss appearance var timeNow = PreHelpers.UnixUtcNow(); double timePassed = 0; if (PlayerPrefsWrapper.HasKey("BossRoomTimedIntervalStarted")) { timePassed = timeNow - PlayerPrefsWrapper.GetDouble("BossRoomTimedIntervalStarted"); } var intervalInDays = Convert.ToSingle(SettingsManager.GetSettingsItem("BOSS_RESPAWN_TIME", -1)); var intervalInSeconds = intervalInDays * 24 * 60 * 60; // ToDo: check time since boss last appeared if (timePassed > intervalInSeconds) { // Enable torches foreach (var torch in _bossTorches) { torch.EnableTorch(); } return; } } // Check current fairy levels var fairyLevels = GameDataManager.Instance.PlayerFairyLevels(); if (fairyLevels.Length > _bossTorches.Length) { return; } // Enable torches for fairies at high enough level for (var i = 0; i < fairyLevels.Length; i++) { if (fairyLevels[i] >= bossLevel) { _bossTorches[i].EnableTorch(); } } }
//============================================================================= public void ReportScore(System.Int64 Score) { // Report score to GC/GP first #if UNITY_IPHONE if ((IsLoggedIn() == true) && (m_ManagerState == eManagerState.Idle)) { GameCenterBinding.reportScore(Score, ScoreboardID); m_ManagerState = eManagerState.ReportScore; } else { if (ReportScoreFailEvent != null) { ReportScoreFailEvent("Error - not logged in or manager busy"); } } #endif #if UNITY_ANDROID if ((IsLoggedIn() == true) && (m_ManagerState == eManagerState.Idle)) { PlayGameServices.submitScore(ScoreboardIDAndroid, Score); m_ManagerState = eManagerState.ReportScore; } else { if (ReportScoreFailEvent != null) { ReportScoreFailEvent("Error - not logged in or manager busy"); } } #endif // Now report score to playtomic system along with any custom parameters if (IsPlayerRegistered() == false) { return; } #if UNITY_EDITOR string sourceType = "Editor"; #elif UNITY_IPHONE string sourceType = "iOS"; #elif UNITY_ANDROID string sourceType = "iOS"; //"Android"; #else string sourceType = "Unknown"; #endif string CurCountry = PreHelpers.GetCountryCode(); PlayerScore NewScore = new PlayerScore { playername = GetPlayerName(), playerid = GetPlayerID(), points = Score, table = ScoreboardID, allowduplicates = false, source = sourceType, fields = new PDictionary { { "country", CurCountry } } }; Playtomic.Leaderboards.Save(NewScore, ScoreSubmitComplete); }
//============================================================================= IEnumerator LoadDataAndSaveToPref(string dataKey, string dataFilename, string uid) { // Save data as a file string DocPath = PreHelpers.GetFileFolderPath(); string FilePath = DocPath + dataFilename + ".txt"; IRequest req = null; if (uid != null) { req = PlayerWS.GetPlayerData(dataKey, uid); } else { req = PlayerWS.RestorePlayerData(dataKey); } yield return(StartCoroutine(req)); if (req.Status != RequestStatus.STATUS_OK) { Debug.Log("Error downloading friend data for key: " + dataKey + " - " + req.Error); DataLoaded = false; // Remove existing file File.Delete(FilePath); } else { // Retrieve data as JSON Dictionary <string, object> OutDict = req.Result as Dictionary <string, object>; JSON DataOut = new JSON(); DataOut.fields = OutDict; string OutString = DataOut.serialized; // Is it a valid file? (contains JSON data and not just {}) if (OutString.Length > 8) { DataLoaded = true; } else { DataLoaded = false; } if (DataLoaded) { Debug.Log("Data downloaded ok for key: " + dataKey + " (" + OutString.Length + ")"); // Open/create file PlayerPrefs.SetString(dataFilename, OutString); } else { // Remove existing file PlayerPrefs.DeleteKey(dataFilename); Debug.Log("Data for key is empty: " + dataKey + " (" + OutString.Length + ")"); } } }
//============================================================================= IEnumerator GetLiveData(int Version, string URL) { WWW GameDataWWW = new WWW(URL); yield return(GameDataWWW); uint NewGameDataChecksum = 0; // Find checksum int ChecksumIndex = URL.IndexOf("wfs2_"); if (ChecksumIndex != -1) { try { NewGameDataChecksum = uint.Parse(URL.Substring(ChecksumIndex + 5, 8), System.Globalization.NumberStyles.HexNumber); } catch { NewGameDataChecksum = 0; } } if (String.IsNullOrEmpty(GameDataWWW.error) && (GameDataWWW.bytes != null)) { UnityEngine.Debug.Log("Updated Game Data OK"); // Make sure checksum matches uint Checksum = HelperChecksum.GetChecksum(GameDataWWW.bytes); if (Checksum == NewGameDataChecksum) { // Save file string DocPath = PreHelpers.GetFileFolderPath(); string FilePath = DocPath + "wfs2.zip"; // Write file FileStream fs = null; try { fs = new FileStream(FilePath, FileMode.Create); } catch { Debug.Log("GameData file creation exception: " + FilePath); } if (fs != null) { PlayerPrefs.SetInt("LiveDataVersion", Version); BinaryWriter CurFile = new BinaryWriter(fs); CurFile.Write(GameDataWWW.bytes); // Close file CurFile.Close(); fs.Close(); // Unzip into local data files //PreHelpers.LoadGameDataUpdate(); } } else { UnityEngine.Debug.Log("Game Data update checksum mismatch: " + Checksum.ToString("X") + " " + NewGameDataChecksum.ToString("X")); } } else { UnityEngine.Debug.Log("Game Data updated error: " + GameDataWWW.error); } }
//===================================================== void LoadLiveUpdate() { string DocPath = PreHelpers.GetFileFolderPath(); string FilePath = DocPath + "wfs2.zip"; if (System.IO.File.Exists(FilePath) == false) { return; } // Read file FileStream fs = null; try { fs = new FileStream(FilePath, FileMode.Open); } catch { Debug.Log("GameData file open exception: " + FilePath); } if (fs != null) { try { // Read zip file ZipFile zf = new ZipFile(fs); int numFiles = 0; if (zf.TestArchive(true) == false) { Debug.Log("Zip file failed integrity check!"); zf.IsStreamOwner = false; zf.Close(); fs.Close(); } else { foreach (ZipEntry zipEntry in zf) { // Ignore directories if (!zipEntry.IsFile) { continue; } String entryFileName = zipEntry.Name; // Skip .DS_Store files if (entryFileName.Contains("DS_Store")) { continue; } Debug.Log("Unpacking zip file entry: " + entryFileName); byte[] buffer = new byte[4096]; // 4K is optimum Stream zipStream = zf.GetInputStream(zipEntry); // Manipulate the output filename here as desired. string fullZipToPath = PreHelpers.GetFileFolderPath() + Path.GetFileName(entryFileName); // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size // of the file, but does not waste memory. // The "using" will close the stream even if an exception occurs. using (FileStream streamWriter = System.IO.File.Create(fullZipToPath)) { StreamUtils.Copy(zipStream, streamWriter, buffer); } numFiles++; } zf.IsStreamOwner = false; zf.Close(); fs.Close(); // If we've unpacked the local files (at least 13) then start using local spreadsheets data Debug.Log("Zip updated with " + numFiles + " files (needs 13)"); if (numFiles >= 13) { PlayerPrefs.SetInt(PreHelpers.GetLiveDataVersionString(), 1); } // Reload managers TextManager.Reload(); SettingsManager.Reload(); TradingCardItemsManager.Reload(); ClothingItemsManager.Reload(); FairyItemsManager.Reload(); WildMagicItemsManager.Reload(); NPCItemsManager.Reload(); } } catch { Debug.Log("Zip file error!"); } // Remove zip file Debug.Log("Removing zip file"); System.IO.File.Delete(FilePath); } }
//============================================================================= static bool LoadLanguage() { string language_type = PreHelpers.GetLanguageCode(); Debug.Log("Loaded localisations for language code: '" + language_type + "'"); if (m_bLanguageLoaded == true) { return(true); } m_bLanguageLoaded = true; StringReader reader = null; if (PlayerPrefs.HasKey(PreHelpers.GetLiveDataVersionString()) && false) { // Load locally string DocPath = PreHelpers.GetFileFolderPath(); string FilePath = DocPath + "Localisations_" + language_type.ToUpper() + ".txt"; // Read file string Contents = null; try { StreamReader CurFile = new StreamReader(FilePath); Contents = CurFile.ReadToEnd(); // Close file CurFile.Dispose(); } catch { PlayerPrefs.DeleteKey(PreHelpers.GetLiveDataVersionString()); } reader = new StringReader(Contents); } else { // Load from resources string fullpath = "Languages/Localisations_" + language_type.ToUpper(); TextAsset textAsset = (TextAsset)Resources.Load(fullpath, typeof(TextAsset)); if (textAsset == null) { Debug.Log(fullpath + " file not found."); return(false); } reader = new StringReader(textAsset.text); } // create the text hash table if one doesn't exist if (textTable == null) { textTable = new Dictionary <string, string>(); } // clear the dictionary textTable.Clear(); string key = string.Empty; string val = string.Empty; string multival = string.Empty; string intext = string.Empty; // First parse through rows until we find the starting one // The 'localisations.txt' file has loads of info at the start that we can ignore as it's all excel settings int RowCount = 0; while (true) { intext = reader.ReadLine(); int Idx = intext.IndexOf("<Row"); if (Idx != -1) { RowCount++; } if (RowCount == 7) { break; } } // Here's an example of a 'row' from the localisations.txt file containing the various cells /* * <Row> * <Cell ss:StyleID="s32"><Data ss:Type="String">POPUP_CONFIRMATION</Data></Cell> * <Cell><Data ss:Type="Number">7</Data></Cell> * <Cell ss:StyleID="s32"><Data ss:Type="String">Confirm</Data></Cell> * <Cell ss:StyleID="s32"><Data ss:Type="Number">0</Data></Cell> * <Cell ss:StyleID="s32"><Data ss:Type="String">Conferma</Data></Cell> * <Cell ss:StyleID="s31"/> * <Cell ss:StyleID="s31"/> * <Cell ss:StyleID="s31"/> * </Row> */ // Start of text data, begin parsing the rows int Line = 0; while (true) { // Read cell containing text code intext = reader.ReadLine(); // intext might look something like this now: // <Cell ss:StyleID="s32"><Data ss:Type="String">POPUP_CONFIRMATION</Data></Cell> // Find the data in the cell - in this case it's "POPUP_CONFIRMATION" bool bValidKey = false; int Idx4 = intext.IndexOf("><"); if (Idx4 != -1) { int Idx2 = intext.IndexOf(">", Idx4 + 2); if (Idx2 != -1) { int Idx3 = intext.IndexOf("<", Idx2); if (Idx3 != -1) { // String is between Idx2 and Idx3 - this is the text 'key' - "POPUP_CONFIRMATION" key = intext.Substring(Idx2 + 1, Idx3 - Idx2 - 1); bValidKey = true; } } } // If we've found a key continue reading the translation text for this key if (bValidKey) { // Skip until correct language column is reached - each column is a line in the file int ColumnCount = 2; do { multival = reader.ReadLine(); ColumnCount++; } while(ColumnCount <= 2); intext = reader.ReadLine(); bool bValidVal = false; int Idx5 = intext.IndexOf("><"); if (Idx5 != -1) { int Idx6 = intext.IndexOf(">", Idx5 + 2); if (Idx6 != -1) { int Idx7 = intext.IndexOf("<", Idx6); if (Idx7 != -1) { // String is between Idx2 and Idx3 - this is the text 'val' val = intext.Substring(Idx6 + 1, Idx7 - Idx6 - 1); val = val.Replace("(newline)", "\n"); /* Below replacement is now done on server * // Convert newline characters and other special codes * val = val.Replace( " " , "\n" ); * val = val.Replace( "'" , "'" ); * val = val.Replace( """ , "\"" ); * val = val.Replace( "&" , "&" ); * * // Replace microsoft word special chars * val = val.Replace( "’" , "'" ); * val = val.Replace( "–" , "-" ); * val = val.Replace( "‘" , "'" ); * val = val.Replace( "“" , "\"" ); * val = val.Replace( "”" , "\"" ); */ bValidVal = true; } } } if (bValidVal) { //Debug.Log( "Valid Key: " + key + " (" + val + ")" ); try { textTable.Add(key, val); } catch { Debug.LogError("Duplicate key in localisations sheet: " + key + " " + val); } } else { Debug.Log("Invalid Value for key [" + key + "]"); } // Find the end of this row by looking for the start of the next row while (true) { multival = reader.ReadLine(); int Idx = multival.IndexOf("<Row"); if (Idx != -1) { // Found next row, break break; } // End of excel sheet? Idx = multival.IndexOf("Workbook>"); if (Idx != -1) { // Found end of workbook reader.Dispose(); return(true); } } } else { Debug.Log("Invalid Key! " + key); #if UNITY_EDITOR UnityEditor.EditorUtility.DisplayDialog("Error", "Key missing in localisations after:" + key + " - line:" + Line, "OK"); #endif break; } Line++; } reader.Dispose(); return(true); }