private void LoadConfigUsingJson()
    {
        string[] paths = BetterStreamingAssets.GetFiles("\\", "*.txt", SearchOption.AllDirectories);

        for (int n = 0; n < paths.Length; ++n)
        {
            byte[] byteContents   = BetterStreamingAssets.ReadAllBytes(paths[n]);
            string contentsString = System.Text.Encoding.UTF8.GetString(byteContents);

            if ("clientConfig.txt" == paths[n])
            {
                LoadClientConfig(contentsString);
                Debug.Log("load clientconfig");
            }
            else
            if ("serverConfig.txt" == paths[n])
            {
                LoadServerConfig(contentsString);
                C2Session.Instance.OnInit();
            }
            else
            {
                Debug.Log($"zz : {paths[n]}");
            }
        }
    }
示例#2
0
    Color[,] PNGtoArray(string folder, string file)
    {
        //Texture2D tex = null;
        byte[] fileData;

        BetterStreamingAssets.Initialize();


        fileData = BetterStreamingAssets.ReadAllBytes(folder + "/" + file + ".png");
        tex      = new Texture2D(2, 2);
        tex.LoadImage(fileData);


        Color[,] Array = new Color[tex.width, tex.height];

        for (int i = 0; i < tex.width; i++)
        {
            for (int j = 0; j < tex.height; j++)
            {
                Array[i, j] = (tex.GetPixel(i, j));
            }
        }

        return(Array);
    }
示例#3
0
    string dbFileName = "/inout.db"; //@"/innerData.db";


    public void Init()
    {
        dbPath = Application.persistentDataPath + dbFileName;

        if (!PlayerPrefs.HasKey("dbPath"))
        {
            PlayerPrefs.SetString("dbPath", dbPath);
        }

        Common.GetInstance.PrintLog('w', "SqliteMgr", dbPath);

        //check DB file exist
        //Debug.LogWarning("copy db files");
        if (ConstValue.CLEARDB && File.Exists(dbPath)) //remove db file on dev mode
        {
            File.Delete(dbPath);
        }

        if (!File.Exists(dbPath))
        {
            BetterStreamingAssets.Initialize();
            byte[] readByte = BetterStreamingAssets.ReadAllBytes(dbFileName);
            File.WriteAllBytes(dbPath, readByte);
        }
    }
示例#4
0
        /// <summary>
        /// 线程异步读取文件
        /// </summary>
        /// <param name="relativeStreamingAssetPath"></param>
        /// <param name="compelted"></param>
        /// <returns></returns>
        public static Action ReadFileAsync(string relativeStreamingAssetPath, Action <byte[]> compelted)
        {
            var filePath            = PathUtils.TryGetTargetFilePath(relativeStreamingAssetPath);
            ThreadJob <byte[]> task = new ThreadJob <byte[]>(() =>
            {
#if UNITY_EDITOR || UNITY_IPHONE
                var bytes = File.ReadAllBytes(filePath);
                bytes     = XOR.Decrypt(bytes);
                return(bytes);
#elif UNITY_ANDROID
                var bytes = BetterStreamingAssets.ReadAllBytes(streamingAssetPath);
                bytes     = XOR.Decrypt(bytes);
                return(bytes);
#else
                var bytes = File.ReadAllBytes(filePath);
                bytes     = XOR.Decrypt(bytes);
                return(bytes);
#endif
            });
            Action doStart = () =>
            {
                task.ContinueOnUIThread((r) =>
                {
                    compelted(r.Result);
                });
                task.Start();
            };

            doStart();
            return(() =>
            {
                task.Abort();
            });
        }
        public void TestAssetBundleMatchRawData()
        {
            NeedsTestData();

            foreach (var size in SizesMB)
            {
                foreach (var format in new[] { "raw_uncompressable_{0:00}MB.bytes", "raw_uncompressable_{0:00}MB.bytes" })
                {
                    var name           = string.Format(format, size);
                    var referenceBytes = BetterStreamingAssets.ReadAllBytes(TestDirName + "/" + name);
                    Assert.AreEqual(size * 1024 * 1024, referenceBytes.Length);

                    foreach (var suffix in BundlesLabels)
                    {
                        var bundleName = Path.GetFileNameWithoutExtension(name).Replace("raw_", "bundle_") + "." + suffix;

                        var bundle = BetterStreamingAssets.LoadAssetBundle(TestDirName + "/" + bundleName);
                        try
                        {
                            var textAsset = (TextAsset)bundle.LoadAllAssets()[0];
                            Assert.AreEqual(Path.GetFileNameWithoutExtension(name), textAsset.name, bundleName);

                            var bytes = textAsset.bytes;
                            Assert.Zero(memcmp(bytes, referenceBytes, bytes.Length), bundleName);
                        }
                        finally
                        {
                            bundle.Unload(true);
                        }
                    }
                }
            }
        }
示例#6
0
    bool LoadByteCodeByFile()
    {
        string szPathName = "test.code";

        print_error("开始加载, 路径:" + szPathName);
        try
        {
            BetterStreamingAssets.Initialize();

            byte[] fileData = BetterStreamingAssets.ReadAllBytes(szPathName);
            if (fileData != null && fileData.Length > 0)
            {
                print_error("加载成功:" + szPathName + ", 字节大小:" + fileData.Length.ToString());
                FCLibHelper.fc_set_code_data(fileData, fileData.Length, 0);
                OnAfterLoadScriptData();
                return(true);
            }
        }
        catch (Exception e)
        {
            print_error(e.ToString());
        }
        print_error("加载失败:" + szPathName);
        return(false);
    }
示例#7
0
    private void CopyLevelToPersistent(string localPath)
    {
        string pathToPersistent = System.IO.Path.GetFullPath(Application.persistentDataPath + "/niveaux");

        for (int i = 1; i <= 30; i++)
        {
            byte[] data = BetterStreamingAssets.ReadAllBytes("/niveaux/" + localPath + i + ".txt");
            System.IO.File.WriteAllBytes(pathToPersistent + localPath + i + ".txt", data);
        }
    }
示例#8
0
    public Texture2D GetImage(string name)
    {
        Texture2D tex = new Texture2D(2048, 2048, TextureFormat.RGBA32, false);

        byte[] texture = BetterStreamingAssets.ReadAllBytes(mainPaths[selectedLang] + @"Textures/" + name);
        tex.LoadImage(texture);
        tex.Compress(true);
        tex.Apply();
        return(tex);
    }
示例#9
0
 /// <summary>
 /// 读取文件内容
 /// </summary>
 /// <param name="filePath"></param>
 /// <param name="isUseSysIO"></param>
 /// <returns></returns>
 static private byte[] ReadFileAllBytes(string filePath, bool isUseSysIO)
 {
     if (isUseSysIO)
     {
         return(File.ReadAllBytes(filePath));
     }
     else
     {
         return(BetterStreamingAssets.ReadAllBytes(filePath));
     }
 }
        public void TestReadAllBytesCompareWithProjectFiles()
        {
            var files = GetRealFiles("/", null, SearchOption.AllDirectories);

            foreach (var f in files)
            {
                var a = File.ReadAllBytes("Assets/StreamingAssets/" + f);
                var b = BetterStreamingAssets.ReadAllBytes(f);
                Assert.AreEqual(a.Length, b.Length);
                Assert.Zero(memcmp(a, b, a.Length));
            }

            Assert.Throws <FileNotFoundException>(() => BetterStreamingAssets.ReadAllBytes("FileThatShouldNotExist"));
        }
示例#11
0
        /// <summary>
        /// 同步读取文件
        /// </summary>
        /// <param name="relativeStreamingAssetPath"></param>
        /// <returns></returns>
        public static byte[] ReadFileSync(string relativeStreamingAssetPath)
        {
            byte[] bytes = null;

            var filePath = PathUtils.TryGetTargetFilePath(relativeStreamingAssetPath);

#if UNITY_EDITOR || UNITY_IPHONE
            bytes = File.ReadAllBytes(filePath);
#elif UNITY_ANDROID
            bytes = BetterStreamingAssets.ReadAllBytes(streamingAssetPath);
#endif
            byte[] newbytes = XOR.Decrypt(bytes);
            return(newbytes);
        }
 private void ResolvePlatformLimapp(out byte[] data, out string fileName)
 {
     if (Application.platform == RuntimePlatform.Android)
     {
         data     = BetterStreamingAssets.ReadAllBytes(PreviewConfig.AndroidAppFullName);
         fileName = PreviewConfig.AndroidAppFullName;
     }
     else
     {
         var limappPath = Application.isEditor ? PreviewConfig.EmulatorPath : PreviewConfig.AndroidPath;
         fileName = Path.GetFileName(limappPath);
         data     = File.ReadAllBytes(limappPath);
     }
 }
示例#13
0
    /// <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;
    }
示例#14
0
    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();
                    }
                }
            }
        }
示例#16
0
    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);
        }
    }
示例#17
0
    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
    }
    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);
    }
示例#19
0
    /// <summary>
    /// Obtiene las imagenes que esten en la carpeta Imagen del movil
    /// </summary>
    public void ObtenerDeImage()
    {
        string path = Application.persistentDataPath.Substring(0, Application.persistentDataPath.IndexOf("/Android")) + "/Imagen";

        BetterStreamingAssets.Initialize();

        if (Application.platform == RuntimePlatform.Android)
        {
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
                string[] dirs = BetterStreamingAssets.GetFiles("Otratextura", "*.*");
                foreach (string nombreimage in dirs)
                {
                    if (!nombreimage.Contains(".meta"))
                    {
                        //Se almacena la imagen de prueba
                        string[]  subfile = nombreimage.Split('/');
                        Texture2D ss      = new Texture2D(2, 2);
                        byte[]    b       = BetterStreamingAssets.ReadAllBytes(nombreimage);
                        ss.LoadImage(b);
                        File.WriteAllBytes(path + "/Final.png", b);
                        File.OpenRead(path + "/Final.png");
                        //Se fuerza un escaneo de la imagen de prueba
                        using (AndroidJavaClass jcUnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
                            using (AndroidJavaObject joActivity = jcUnityPlayer.GetStatic <AndroidJavaObject>("currentActivity"))
                                using (AndroidJavaObject joContext = joActivity.Call <AndroidJavaObject>("getApplicationContext"))
                                    using (AndroidJavaClass jcMediaScannerConnection = new AndroidJavaClass("android.media.MediaScannerConnection"))
                                        using (AndroidJavaClass jcEnvironment = new AndroidJavaClass("android.os.Environment"))
                                            using (AndroidJavaObject joExDir = jcEnvironment.CallStatic <AndroidJavaObject>("getExternalStorageDirectory"))
                                            {
                                                jcMediaScannerConnection.CallStatic("scanFile", joContext, new string[] { path + "/Final.png" }, null, null);
                                            }
                    }
                }
                //aviso de carpeta creada
                Menu_aviso.SetActive(true);
                GameObject aviso = GameObject.Find("Aviso");
                aviso.GetComponent <Text>().text = "Agrege las fotos a la carpeta Imagen en tu galería y vuelve a pulsar";
            }
            else
            {
                string[] dirs = System.IO.Directory.GetFiles(path);

                if (dirs.Length == 1)
                {
                    //no hay fotos que añadir
                    Menu_aviso.SetActive(true);
                    GameObject aviso = GameObject.Find("Aviso");
                    aviso.GetComponent <Text>().text = "No hay fotos que agregar";
                }
                else
                {
                    bool ninguna_nueva = true;
                    foreach (string nombreimage in dirs)
                    {
                        if (!nombreimage.Contains(".meta") && (nombreimage.Contains(".png") || nombreimage.Contains(".jpg")) && !nombreimage.Contains("Final.png"))
                        {
                            //Se comprueba si las fotos han sido ya guardadas en la BBDD
                            string[] sub            = nombreimage.Split('/');
                            string[] separador      = sub[sub.Length - 1].Split('.');
                            string   nombrecorrecto = separador[0];
                            Textura  textura        = ds.TexturaEnBaseDeDatos(nombrecorrecto);
                            if (textura == null)
                            {
                                //si no llega aqui es que no habia nuevas fotos que añadir
                                ninguna_nueva = false;
                                byte[] b     = File.ReadAllBytes(nombreimage);
                                int    valor = ds.GetTamtablaTexture();

                                ds.GuardarImagen(b, sub[sub.Length - 1].ToString());
                                Control.AñadirFoto(valor, ds);
                            }
                        }
                    }

                    Menu_aviso.SetActive(true);
                    GameObject aviso = GameObject.Find("Aviso");
                    if (!ninguna_nueva)
                    {
                        aviso.GetComponent <Text>().text = "Se han añadido al menú de textura";
                    }
                    else
                    {
                        aviso.GetComponent <Text>().text = "No habia ninguna nueva foto que añadir";
                    }
                }
            }
        }
    }
示例#20
0
        /// <summary>
        /// 是否存在资源.并且校验hash
        /// </summary>
        /// <param name="platform"></param>
        /// <param name="serverAsset"></param>
        /// <returns></returns>
        static public bool IsExsitAssetWithCheckHash(RuntimePlatform platform, string assetName, string assetHash)
        {
            //本地是否下载过hash文件(之前下到一半就中止了),hash文件只会在
            var persistentHashPath = IPath.Combine(BApplication.persistentDataPath, BApplication.GetPlatformPath(platform), assetHash);

            if (File.Exists(persistentHashPath))
            {
                var hash = FileHelper.GetMurmurHash3(persistentHashPath);
                if (assetHash.Equals(hash))
                {
                    BDebug.Log($"hash文件存在 - {assetName} | hash - {assetHash}");
                    return(true);
                }
                else
                {
                    File.Delete(persistentHashPath);
                }
            }

            //persistent判断
            var persistentAssetPath = IPath.Combine(BApplication.persistentDataPath, BApplication.GetPlatformPath(platform), assetName);

            if (File.Exists(persistentAssetPath))
            {
                var hash = FileHelper.GetMurmurHash3(persistentAssetPath);
                if (assetHash.Equals(hash))
                {
                    BDebug.Log($"persistent存在 - {assetName} | hash - {assetHash}");
                    return(true);
                }
            }


            /************母包资源的判断*************/
            if (Application.isEditor && BDLauncher.Inst.GameConfig.ArtRoot == AssetLoadPathType.DevOpsPublish)
            {
                //devops
                var devopsAssetPath = IPath.Combine(BApplication.DevOpsPublishAssetsPath, BApplication.GetPlatformPath(platform), assetName);
                if (File.Exists(devopsAssetPath))
                {
                    var hash = FileHelper.GetMurmurHash3(devopsAssetPath);
                    if (assetHash.Equals(hash))
                    {
                        BDebug.Log($"devops存在 - {assetName} | hash - {assetHash}");
                        return(true);
                    }
                }
            }
            else
            {
                //Streaming 文件判断,无需Streaming前缀
                var streamingAssetPath = IPath.Combine(BApplication.GetPlatformPath(platform), assetName);
                if (BetterStreamingAssets.FileExists(streamingAssetPath))
                {
                    var bytes = BetterStreamingAssets.ReadAllBytes(streamingAssetPath);
                    var hash  = FileHelper.GetMurmurHash3(bytes);
                    if (assetHash.Equals(hash))
                    {
                        BDebug.Log($"streaming存在 - {assetName} | hash - {assetHash}");
                        return(true);
                    }
                }
            }


            return(false);
        }
示例#21
0
        private IEnumerator TestHarness(ReadMode readMode, string path, TestType testType, int attempts, TestResultDelegate callback)
        {
            var stopwatch = new Stopwatch();

            string[] assetNames = null;

            var streamingAssetsUrl = Path.Combine(StreamingAssetsPath, path).Replace('\\', '/');

            long bytesRead        = 0;
            long maxMemoryPeak    = 0;
            long totalMemoryPeaks = 0;

            for (int i = 0; i < attempts; ++i)
            {
                WWW www = null;

                yield return(Resources.UnloadUnusedAssets());

                GC.Collect();
                GC.WaitForPendingFinalizers();
                yield return(null);

                var memoryUnityBefore = Profiler.GetTotalAllocatedMemoryLong();
                //var memoryMonoBefore = Profiler.GetMonoUsedSizeLong();
                stopwatch.Start();

                if (readMode == ReadMode.WWW)
                {
                    www = new WWW(streamingAssetsUrl);

                    {
                        yield return(www);

                        Profiler.BeginSample(testType.ToString());

                        switch (testType)
                        {
                        case TestType.CheckIfExists:
                            if (!string.IsNullOrEmpty(www.error))
                            {
                                throw new System.Exception(www.error);
                            }
                            break;

                        case TestType.LoadBytes:
                            bytesRead += www.bytes.Length;
                            break;

                        default:
                            throw new NotSupportedException();
                        }
                        Profiler.EndSample();
                    }
                }
                else if (readMode == ReadMode.BSA)
                {
                    Profiler.BeginSample(testType.ToString());

                    switch (testType)
                    {
                    case TestType.CheckIfExists:
                        if (!BetterStreamingAssets.FileExists(path))
                        {
                            throw new System.InvalidOperationException();
                        }
                        break;

                    case TestType.LoadBytes:
                        bytesRead += BetterStreamingAssets.ReadAllBytes(path).Length;
                        break;
                    }

                    Profiler.EndSample();
                }
                else if (readMode == ReadMode.Direct)
                {
                    var p = streamingAssetsUrl;
                    Profiler.BeginSample(testType.ToString());

                    switch (testType)
                    {
                    case TestType.CheckIfExists:
                        if (!File.Exists(p))
                        {
                            throw new System.InvalidOperationException();
                        }
                        break;

                    case TestType.LoadBytes:
                        bytesRead += File.ReadAllBytes(p).Length;
                        break;
                    }

                    Profiler.EndSample();
                }
                stopwatch.Stop();

                var memoryPeak = Math.Max(0, Profiler.GetTotalAllocatedMemoryLong() - memoryUnityBefore);
                // + Math.Max(0, Profiler.GetMonoUsedSizeLong() - memoryMonoBefore);

                maxMemoryPeak     = System.Math.Max(memoryPeak, maxMemoryPeak);
                totalMemoryPeaks += memoryPeak;

                yield return(null);

                if (www != null)
                {
                    www.Dispose();
                }

                yield return(null);
            }

            yield return(Resources.UnloadUnusedAssets());

            GC.Collect();
            GC.WaitForPendingFinalizers();
            yield return(null);

            callback(new TimeSpan(stopwatch.ElapsedTicks / attempts), bytesRead / attempts, totalMemoryPeaks / attempts, maxMemoryPeak, assetNames);
        }