/// <summary> /// Método que crea la base de datos y la rellena. /// </summary> public void CreateDB() { ArrayPow2(); //Creación de tablas si no existen _connection.CreateTable <Textura>(); _connection.CreateTable <Buildings>(); _connection.CreateTable <Numeracion>(); try { if (this.GetTamtablaTexture() == 0) { //Sí la BBDD está vacia carga las texturas de prueba if (Application.platform == RuntimePlatform.Android) { BetterStreamingAssets.Initialize(); string[] dirs = BetterStreamingAssets.GetFiles("texturasInicial", "*.*"); foreach (string nombreimage in dirs) { if (!nombreimage.Contains(".meta") && (nombreimage.Contains(".jpg") || nombreimage.Contains(".png"))) { string[] subfile = nombreimage.Split('/'); GuardarImagen(BetterStreamingAssets.ReadAllBytes(nombreimage), subfile[1]); } } } else { //analiza si hay nuevas fotos de prueba que añadir y las añade string[] dirs = System.IO.Directory.GetFiles(@"Assets/StreamingAssets/texturasInicial"); foreach (string nombreimage in dirs) { if (!nombreimage.Contains(".meta") && (nombreimage.Contains(".jpg") || nombreimage.Contains(".png"))) { string[] subfile = nombreimage.Split('\\'); GuardarImagen(File.ReadAllBytes(@"Assets/StreamingAssets/texturasInicial/" + subfile[1]), subfile[1]); } } } } } catch { Debug.Log("No existe la carpeta TexturaInicial"); } return; }
/// <summary> /// 加载本地的Asset.info /// </summary> private List <AssetItem> LoadLocalAssetInfo(RuntimePlatform platform) { var retList = new List <AssetItem>(); //优先加载persistent的Assets.info var persistentAssetInfoPath = BResources.GetAssetsInfoPath(BApplication.persistentDataPath, platform); if (File.Exists(persistentAssetInfoPath)) { var content = File.ReadAllText(persistentAssetInfoPath); retList = CsvSerializer.DeserializeFromString <List <AssetItem> >(content); } //streaming 和其他的Assets.info else { //根据加载模式不同,寻找不同目录下的其他配置 //打包时,本地会带一份ServerAssets.info以标记当前包携带的资源 var loadArtRoot = BDLauncher.Inst.GameConfig.ArtRoot; switch (loadArtRoot) { case AssetLoadPathType.Persistent: case AssetLoadPathType.StreamingAsset: { //TODO :BSA 读取,不需要Streaming前缀 var steamingAssetsInfoPath = IPath.Combine(BApplication.GetPlatformPath(platform), BResources.ASSETS_INFO_PATH); //var steamingAssetsInfoPath = GetAssetsInfoPath(BDApplication.streamingAssetsPath, platform); if (BetterStreamingAssets.FileExists(steamingAssetsInfoPath)) { var content = BetterStreamingAssets.ReadAllText(steamingAssetsInfoPath); retList = CsvSerializer.DeserializeFromString <List <AssetItem> >(content); } } break; case AssetLoadPathType.DevOpsPublish: { var path = GameConfig.GetLoadPath(loadArtRoot); var devopsAssetInfoPath = BResources.GetAssetsInfoPath(path, platform); if (File.Exists(devopsAssetInfoPath)) { var content = File.ReadAllText(devopsAssetInfoPath); retList = CsvSerializer.DeserializeFromString <List <AssetItem> >(content); } } break; } } return(retList); }
/// <summary> /// Import the list of objects in objectList. /// </summary> protected virtual void Start() { string texto; string arquivo; if (autoLoadOnStart) { //variaveis arquivo = "Models.txt"; Debug.Log(arquivo); BetterStreamingAssets.Initialize(); texto = BetterStreamingAssets.ReadAllText(arquivo); int[] separacoes = new int[2]; int i = 0, cont = 0; //carregar a lista de objectos a importar do { separacoes[0] = i; Debug.Log("Entrou com cont = " + cont); //pega o endereco do modelo for (int j = 0; i < texto.Length && j < 8; i++) { if (texto[i] == '\n' || texto[i] == ' ') { if (j < 1) { separacoes[1] = i; } //Debug.Log(separacoes[j]); j++; } } //configura para carregar o modelo ModelImportInfo mii = new ModelImportInfo(); mii.name = "object" + cont; this.objectsList.Add(mii); this.objectsList[cont].path = texto.Substring(separacoes[0], separacoes[1] - separacoes[0] - 1); if (objectsList[cont].path[objectsList[cont].path.Length - 1] == 10) { objectsList[cont].path = objectsList[cont].path.Substring(0, objectsList[cont].path.Length - 2); } cont++; } while (i < texto.Length); //importar os modelos ImportModelListAsync(objectsList.ToArray()); } }
public void Awake() { if (IsLoaded) { return; } BetterStreamingAssets.Initialize(); GameData = new GameData(this); SaveManager = new SaveManager(); if (SaveManager.SaveExists("save")) { SaveManager.Load("save"); } IsLoaded = true; }
// Start is called before the first frame update void Start() { BetterStreamingAssets.Initialize(); string filePath = System.IO.Path.Combine("term", "obj"); filePath = System.IO.Path.Combine(filePath, SceneManager.GetActiveScene().name + ".txt"); Debug.Log(filePath); string newText = ""; foreach (string item in BetterStreamingAssets.ReadAllLines(filePath)) { newText += item + "\n"; } text.text = newText; }
public void TestOpenReadCompareWithProjectFiles() { var files = GetRealFiles("/", null, SearchOption.AllDirectories); foreach (var f in files) { using (var a = File.OpenRead("Assets/StreamingAssets/" + f)) using (var b = BetterStreamingAssets.OpenRead(f)) { Assert.IsTrue(StreamsEqual(a, b), f); } } Assert.Throws <FileNotFoundException>(() => BetterStreamingAssets.OpenRead("FileThatShouldNotExist")); }
private void Awake() { BetterStreamingAssets.Initialize(); localPath = string.Format("{0}/GymnasticVideo", Application.persistentDataPath); //get gymnastic file list files = new List <string>(); #if UNITY_EDITOR StreamReader sReader = new StreamReader(Path.Combine(Application.streamingAssetsPath, "GymnasticInfo.csv")); #elif UNITY_ANDROID StreamReader sReader = BetterStreamingAssets.OpenText("GymnasticInfo.csv"); #endif string readData; if (sReader == null) { Debug.LogWarning("sReader null"); } else { while ((readData = sReader.ReadLine()) != null) { //Debug.LogWarning("data : " + sReader.ReadLine()); try { files.Add(readData.Split(',')[0]); } catch (Exception e) { //Debug.LogWarning("not pose data in " + idx + " : " + e.Message); } } sReader.Close(); sReader = null; } //end //check directory if (!Directory.Exists(localPath)) { Directory.CreateDirectory(localPath); } //check exist files & file download contain under coroutine StartCoroutine(StartDownLoad()); }
private void Start() { rawImage = gameObject.GetComponent <RawImage>(); imageName = "Image" + gameObject.name + ".png"; BetterStreamingAssets.Initialize(); thisTexture = new Texture2D(100, 100); byte[] bytes = BetterStreamingAssets.ReadAllBytes(imageName); thisTexture.LoadImage(bytes); thisTexture.name = imageName; rawImage.texture = thisTexture; }
//[Test] public void ReadAllBytesZeroFile() { NeedsTestData(); foreach (var path in BetterStreamingAssets.GetFiles(TestDirName, "raw_compressable*", SearchOption.TopDirectoryOnly)) { var bytes = BetterStreamingAssets.ReadAllBytes(path); for (int i = 0; i < bytes.Length; ++i) { if (bytes[i] != 0) { Assert.Fail(); } } } }
void Start() { Application.targetFrameRate = 30; Screen.SetResolution(1280, 720, true); NuitrackManager.GestureRecognizer.OnNewGesturesEvent += AttendGestures; gestureModels = new PoseModel[1]; BetterStreamingAssets.Initialize(); gestureModels[0] = new PoseModel(); gestureModels[0].LoadModel(modelPaths[0]); gestureModel.Add(CustomGestureType.HandsUp, gestureModels[0]); }
public BetterStreamingAssetsTests(string path, bool apkMode) { if (apkMode && !File.Exists(path)) { Assert.Inconclusive("Build for Android and name output: " + path); } if (apkMode) { BetterStreamingAssets.InitializeWithExternalApk(path); } else { BetterStreamingAssets.InitializeWithExternalDirectories(".", path); } }
// Use this for initialization void Start() { BetterStreamingAssets.Initialize(); eventSystem = GetComponent <EventSystem>(); memoryPairing = GetComponent <MemoryPairing>(); //lastselect = new GameObject(); String filepath = "/Json/" + filename; Debug.Log("Reading cards " + filepath); var jsonText = BetterStreamingAssets.ReadAllLines(filepath); foreach (var line in jsonText) { CardPairClass cpc = JsonUtility.FromJson <CardPairClass>(line); CardClass cc1 = new CardClass(); CardClass cc2 = new CardClass(); cc1.cardText = cpc.textA; cc1.audioName = cpc.audioA; cc1.pairNumber = cpc.pairNumber; cc2.cardText = cpc.textB; cc2.audioName = cpc.audioB; cc2.pairNumber = cpc.pairNumber; cardsData.Add(cc1); cardsData.Add(cc2); } Shuffle <CardClass>(cardsData); Debug.Log("Finished loading cards."); int k = 0; for (int i = 0; i < rowCount; i++) { for (int j = 0; j < row1.Count; j++) { currRow = i; currColumn = j; try { StartCoroutine("loadAudio", cardsData[k]); } catch (Exception e) { } k++; } } }
public void LoadExpressions() { if (images == null) { images = new Dictionary <string, Sprite>(); } string nameWithoutAccentuation; foreach (var expressao in expressoes) { if (images.ContainsKey(expressao)) { continue; } if (nome == "André") { nameWithoutAccentuation = "Andre"; } else if (nome == "Valéria") { nameWithoutAccentuation = "Valeria"; } else { nameWithoutAccentuation = nome; } var filePath = CharacterImageLocation + "/" + nameWithoutAccentuation + "/" + expressao + ".png"; //Get path of folder Debug.Log(filePath); if (!BetterStreamingAssets.FileExists(filePath)) { continue; } Texture2D tex = new Texture2D(2, 2); using (var stream = BetterStreamingAssets.OpenRead(filePath)) { MemoryStream ms = new MemoryStream(); stream.CopyTo(ms); tex.LoadImage(ms.ToArray()); images[expressao] = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), new Vector2(0.5f, 0.5f), 100.0f); } } }
public List <string> GetLangs() { List <string> mainLangs = new List <string>(); mainPaths.Clear(); m_allStreamingAssets = BetterStreamingAssets.GetFiles("/", "*", SearchOption.AllDirectories); foreach (string path in m_allStreamingAssets) { if (path.Contains("main")) { mainLangs.Add(BetterStreamingAssets.ReadAllLines(path)[0]); mainPaths.Add(path.Replace("main", "")); } } return(mainLangs); }
//Needed for damn Android StreamingAssets public void LoadCSVPaletteFromStreamingAssets(string path) { if (Application.platform == RuntimePlatform.Android) //f*cking Android gotta be special { try{ string encodedString = BetterStreamingAssets.ReadAllText(path); string filename = getPaletteNameFromFilePath(path); LoadCSVPaletteFromEncodedString(pc.newPalette(true), encodedString, filename); } catch (Exception e) { Debug.LogWarning("Failed to load CSV: " + path); return; } } else { LoadCSVPalette(pc.newPalette(true), path); } }
public void LoadLocalDB() { string[] jsonFiles = BetterStreamingAssets.GetFiles("\\LocalDB", "*.txt", SearchOption.AllDirectories); for (int n = 0; n < jsonFiles.Length; ++n) { byte[] byteContents = BetterStreamingAssets.ReadAllBytes(jsonFiles[n]); string dbText = System.Text.Encoding.UTF8.GetString(byteContents); //string dbText = jsonFiles[n]; // 스트링에 로드된 텍스트 에셋을 저장 Debug.Log(dbText); Schema schema = JsonMapper.ToObject <Schema>(dbText); // 맵퍼를 이용해서, 텍스트를 매핑. localDatabase.Add(schema.nickname, schema); } }
private void TestGetFiles(string dir, string pattern, SearchOption opt, int minCount, int maxCount) { var files = GetRealFiles(dir, pattern, opt); var otherFiles = BetterStreamingAssets.GetFiles(dir, pattern, opt); System.Array.Sort(files); System.Array.Sort(otherFiles); Assert.AreEqual(files.Length, otherFiles.Length); Assert.GreaterOrEqual(files.Length, minCount); Assert.LessOrEqual(files.Length, maxCount); for (int i = 0; i < files.Length; ++i) { Assert.AreEqual(files[i], otherFiles[i]); } }
private void loadLanguages() { if (!BetterStreamingAssets.FileExists("/lang/" + nameLanguagesFile + ".json")) { Debug.LogErrorFormat("Streaming asset not found: {0}", "/lang/" + nameLanguagesFile + ".json"); } else { json = BetterStreamingAssets.ReadAllText("/lang/" + nameLanguagesFile + ".json"); lang = JsonUtility.FromJson <Languages>(json); if (interfaceLanguages != null) { interfaceLanguages.onChangeLanguage(); } } }
//Called by Central public void LoadLanguage(string languageCode) { string path = "Languages/" + languageCode + ".xml"; if (!BetterStreamingAssets.FileExists(path)) { Debug.LogErrorFormat("Streaming asset not found: {0}", path); } else { using (var stream = BetterStreamingAssets.OpenRead(path)) { var serializer = new System.Xml.Serialization.XmlSerializer(typeof(LanguageContainer)); LoadedLanguage = (LanguageContainer)serializer.Deserialize(stream); } OnNewLanguageLoaded.Invoke(); } }
// Use this for initialization public void Start() { var levelReached = PlayerPrefs.GetInt("levelReached", 0); BetterStreamingAssets.Initialize(); var paths = BetterStreamingAssets.GetFiles("/", "*TD.json", SearchOption.TopDirectoryOnly); JSONObject customLevels = LevelManager.GetCustomLevels(); var i = 0; LevelButtons = new LevelItem[paths.Length + customLevels.Count + 1]; foreach (var path in paths) { var fname = path.Split('_')[0]; var level = Instantiate(LevelButton, transform); var levelItem = level.GetComponent <LevelItem>(); levelItem.SetName(i.ToString()); levelItem.SetFilename(fname); levelItem.IsCustom = false; if (i <= levelReached) { levelItem.SetInteractable(true); } LevelButtons[i] = levelItem; i++; } for (int j = 0; j < customLevels.Count; j++) { JSONObject jsonLevel = customLevels[j]; var level = Instantiate(LevelButton, transform); var levelItem = level.GetComponent <LevelItem>(); levelItem.IsCustom = true; levelItem.SetName("C"); levelItem.SetFilename(jsonLevel["Name"].str); levelItem.SetInteractable(true); LevelButtons[i] = levelItem; i++; } }
private void loadCards() { var jsonFiles = BetterStreamingAssets.GetFiles("Json").Where(x => Path.GetExtension(x) == ".json").ToList(); foreach (string level in jsonFiles) { Debug.Log("Found file"); Debug.Log("Reading " + level); var jsonText = BetterStreamingAssets.ReadAllLines(level); foreach (var line in jsonText) { CardPairClass cpc = JsonUtility.FromJson <CardPairClass>(line); cardsData.Add(cpc); } } SortCards(); Debug.Log("Finished loading cards."); }
public Texture2D LoadTexture(string FilePath) { // Load a PNG or JPG file from disk to a Texture2D // Returns null if load fails Texture2D Tex2D; byte[] FileData; if (BetterStreamingAssets.FileExists(FilePath)) { FileData = BetterStreamingAssets.ReadAllBytes(FilePath); Tex2D = new Texture2D(2, 2); // Create new "empty" texture if (Tex2D.LoadImage(FileData)) // Load the imagedata into the texture (size is set automatically) { return(Tex2D); // If data = readable -> return texture } } return(null); // Return null if load failed }
private void InitializeLevelDirectory() { if (!System.IO.Directory.Exists(Application.persistentDataPath + "/niveaux")) { string pathToPersistent = System.IO.Path.GetFullPath(Application.persistentDataPath + "/niveaux"); System.IO.Directory.CreateDirectory(pathToPersistent + "/facile/lettres"); System.IO.Directory.CreateDirectory(pathToPersistent + "/facile/nombres"); System.IO.Directory.CreateDirectory(pathToPersistent + "/moyen/lettres"); System.IO.Directory.CreateDirectory(pathToPersistent + "/moyen/nombres"); System.IO.Directory.CreateDirectory(pathToPersistent + "/difficile"); BetterStreamingAssets.Initialize(); string localPath; foreach (string difficulty in new string[3] { "facile", "moyen", "difficile" }) { if (difficulty == "facile" || difficulty == "moyen") { foreach (string type in new string[2] { "nombres", "lettres" }) { localPath = "/" + difficulty + "/" + type + "/"; Debug.Log("Writing : " + localPath); CopyLevelToPersistent(localPath); } } else { localPath = "/" + difficulty + "/"; Debug.Log("Writing : " + localPath); CopyLevelToPersistent(localPath); } } } }
public static void init() { if (!isInitialized) { if (!BetterStreamingAssets.FileExists(questionsPath)) { Debug.Log("Could not find questions file!"); throw new FileNotFoundException("Could not find questions file!"); } string[] questionsFile = BetterStreamingAssets.ReadAllLines(questionsPath); string[] csvQuestions = String.Join(";", questionsFile).Split('#'); List <Question> questionList = new List <Question>(); foreach (string questionString in csvQuestions) { questionList.Add(new Question(questionString)); } questionList.Shuffle(); questions = new Queue <Question>(questionList); isInitialized = true; } }
public Sprite LoadPortrait() { if (portrait != null) { return(portrait); } var filePath = CharacterPortraitLocation + id + ".png"; //Get path of folder using (var stream = BetterStreamingAssets.OpenRead(filePath)) { MemoryStream ms = new MemoryStream(); stream.CopyTo(ms); Texture2D tex = new Texture2D(100, 100); tex.LoadImage(ms.ToArray()); portrait = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), new Vector2(0.5f, 0.5f), 100.0f); } return(portrait); }
private void ReadJson(string fileName) { var settings = new JsonSerializerSettings(); BetterStreamingAssets.Initialize(); #if UNITY_EDITOR //jsonPath = Application.streamingAssetsPath + "/"+fileName+".json"; #endif //jsonStrng = File.ReadAllText(jsonPath); jsonStrng = BetterStreamingAssets.ReadAllText("/" + fileName + ".json"); if (jsonStrng != null) { Leveldata = JsonConvert.DeserializeObject <LevelData>(jsonStrng, settings); } else { Debug.Log("JSON File not found "); } }
public static void Load() { BetterStreamingAssets.Initialize(); listaDados.Clear(); //path = Application.streamingAssetsPath + '/' + arquivo; var jsonText = BetterStreamingAssets.ReadAllLines(arquivo); foreach (var line in jsonText) { DadosJogo DadosJson = JsonUtility.FromJson <DadosJogo>(line); DadosJogo dados = new DadosJogo(); dados.pergunta = DadosJson.pergunta; dados.resposta = DadosJson.resposta; dados.r2 = DadosJson.r2; dados.r3 = DadosJson.r3; dados.r4 = DadosJson.r4; dados.dica = DadosJson.dica; dados.nivel = DadosJson.nivel; listaDados.Add(dados); } /*using (StreamReader sr = new StreamReader(path)) * { * while(sr.Peek() >= 0) * { * DadosJogo DadosJson = JsonUtility.FromJson<DadosJogo>(sr.ReadLine()); * DadosJogo dados = new DadosJogo(); * dados.pergunta = DadosJson.pergunta; * dados.resposta = DadosJson.resposta; * dados.r2 = DadosJson.r2; * dados.r3 = DadosJson.r3; * dados.r4 = DadosJson.r4; * dados.dica = DadosJson.dica; * dados.nivel = DadosJson.nivel; * listaDados.Add(dados); * } * }*/ }
internal static void LoadFileData(Action callback = null) { #if !UNITY_ANDROID Stream GenerateStreamFromStreamingAsset(string fileName) { var filePath = Path.Combine(Application.streamingAssetsPath, fileName); var stream = File.Open(filePath, FileMode.Open, FileAccess.Read); return(stream); } #else BetterStreamingAssets.Initialize(); Stream GenerateStreamFromStreamingAsset(string fileName) { var stream = BetterStreamingAssets.OpenRead(fileName); return(stream); } #endif Stream characterDataStream = GenerateStreamFromStreamingAsset("character_data.json"); Stream locationDataStream = GenerateStreamFromStreamingAsset("location_data.json"); // SCENES ARE BEING LOADED FROM A CSV INSTEAD OF FROM AN .ODS // BECAUSE ANDROID'S STREAMING ASSETS ARE A PAIN IN THE BUTT, // AND THE TOOL I FOUND TO SOLVE THAT (BETTER STREAMING ASSETS) // DOESN'T SUPPORT LOADING COMPRESSED FILES, AND AN .ODS FILE // IS A COMPRESSED FILE. Stream scenesStream = GenerateStreamFromStreamingAsset("scenes.csv"); Stream adventuresStream = GenerateStreamFromStreamingAsset("adventures.csv"); Data.FileData = Run.LoadGameData(characterDataStream, locationDataStream, scenesStream, adventuresStream, callback); characterDataStream.Close(); locationDataStream.Close(); scenesStream.Close(); }
/// <summary> /// Import the list of objects in objectList. /// </summary> protected virtual void Start() { if (autoLoadOnStart) { BetterStreamingAssets.Initialize(); objectsList[0].path = BetterStreamingAssets.ReadAllText("path.txt"); //resolve problemas caso o .txt tenha sido criado em um linux if (objectsList[0].path[objectsList[0].path.Length - 1] == 10) { objectsList[0].path = objectsList[0].path.Substring(0, objectsList[0].path.Length - 2); } /* * objectsList[0].loaderOptions.modelScaling = 0.1f; * objectsList[0].loaderOptions.localEulerAngles.x = 90; * objectsList[0].loaderOptions.localPosition.y = 0.7f; */ ImportModelListAsync(objectsList.ToArray()); } }
protected bool LoadByteCodeByFile(OnLoadScriptByteCode pCallBack) { string szPathName = "test.code"; print_error("开始加载, 路径:" + szPathName); try { BetterStreamingAssets.Initialize(); byte[] fileData = BetterStreamingAssets.ReadAllBytes(szPathName); if (fileData != null && fileData.Length > 0) { print_error("加载成功, Path:" + szPathName + ", 文件大小:" + fileData.Length); } pCallBack(fileData); return(true); } catch (Exception e) { print_error(e.ToString()); } print_error("加载失败:" + szPathName); return(false); }