Esempio n. 1
0
 public AsyncStateCoroutine(WaitForEndOfFrame value)
 {
     _enumerator = YieldToEnumerable(value).GetEnumerator();
 }
Esempio n. 2
0
 public static SimpleCoroutineAwaiter GetAwaiter(this WaitForEndOfFrame instruction)
 {
     return(GetAwaiterReturnVoid(instruction));
 }
Esempio n. 3
0
    private IEnumerator CallPluginAtEndOfFrames()
    {
        if (processingRunning)
        {
            Debug.LogError("CallPluginAtEndOfFrames invoked while already running.");
            yield break;
        }

        // Only run while the video is playing.
        bool running = true;

        processingRunning = true;
        exitProcessing    = false;
        WaitForEndOfFrame wfeof = new WaitForEndOfFrame();

        while (running)
        {
            // Wait until all frame rendering is done
            yield return(wfeof);

            if (exitProcessing)
            {
                running = false;
                break;
            }

            if (videoPlayerPtr != IntPtr.Zero)
            {
                CreateTextureForVideoMaybe();
            }

            IntPtr tex = GetRenderableTextureId(videoPlayerPtr);
            currentTexture = 0;
            for (int i = 0; i < videoTextures.Length; i++)
            {
                if (tex == videoTextures[i].GetNativeTexturePtr())
                {
                    currentTexture = i;
                }
            }

            if (!VideoReady)
            {
                continue;
            }
            else if (framecount > 1 && PlayerState == VideoPlayerState.Ended)
            {
                running = false;
            }

            IssuePlayerEvent(RenderCommand.UpdateVideo);
            IssuePlayerEvent(RenderCommand.RenderMono);

            int w = GetWidth(videoPlayerPtr);
            int h = GetHeight(videoPlayerPtr);
            // Limit total pixel count to the same as 2160p.
            // 3840 * 2160 == 2880 * 2880
            if (w * h > 2880 * 2880)
            {
                // Clamp the max resolution preserving aspect ratio.
                float aspectRoot = (float)Math.Sqrt(w / h);
                w = (int)(2880 * aspectRoot);
                h = (int)(2880 / aspectRoot);
            }
            texWidth  = w;
            texHeight = h;

            if ((int)framecount % 30 == 0)
            {
                UpdateStatusText();
            }

            long bp = BufferedPosition;
            if (bp != lastBufferedPosition)
            {
                lastBufferedPosition = bp;
                UpdateStatusText();
            }
        }
        processingRunning = false;
    }
Esempio n. 4
0
 void Awake()
 {
     mWaitForEndOfFrame = new WaitForEndOfFrame();
     Loading            = true;
     StartCoroutine(LoadScenes());
 }
    private IEnumerator ProgressLevelCoroutine(Transform teleportPoint)
    {
        canProgressLevel = false;
        Player.instance.state.canMove = false;
        Player.instance.SetHealth(Player.instance.health + 1);
        if (!firsttime)
        {
            CameraManager.instance.RequestCameraFade(0.2f, true);
            yield return(new WaitForSeconds(0.4f));

            CameraManager.instance.RequestCameraFade(0.2f, false);
            gameplayCamera.gameObject.SetActive(false);
            levelEndCamera.gameObject.SetActive(true);
            allanimator.Play(0);
            heroAnimator.SetBool("IsWalking", true);
            yield return(new WaitForSeconds(4f));

            CameraManager.instance.RequestCameraFade(0.4f, true);
            yield return(new WaitForSeconds(1.5f));

            gameplayCamera.gameObject.SetActive(true);
            levelEndCamera.gameObject.SetActive(false);
        }

        levelNumber++;
        onPassChanged(levelNumber);

        if (levelNumber == maxLevelNumber)
        {
            GameWin();
            yield break;
        }

        yield return(new WaitForSeconds(0.6f));

        CameraManager.instance.RequestCameraFade(0.4f, false);
        Player.instance.gameObject.transform.position = teleportPoint.position;
        firsttime = false;

        currentDayTime = DayTimeEnum.day;
        onDayTimeChanged(currentDayTime);
        yield return(new WaitForSeconds(0.5f));

        var waitEOF = new WaitForEndOfFrame();

        timeLeft = dayDuration;
        while (timeLeft > 0)
        {
            onDayTimeLeftChanged(timeLeft);
            yield return(waitEOF);

            timeLeft -= Time.deltaTime;
        }

        currentDayTime = DayTimeEnum.night;
        onDayTimeChanged(currentDayTime);
        yield return(new WaitForSeconds(0.5f));

        for (int i = 0; i < Inventory.instance.grid.gridSize.y; i++)
        {
            for (int ii = 0; ii < Inventory.instance.grid.gridSize.x; ii++)
            {
                Inventory.instance.grid.slotPrefabs[ii + i * 9].GetComponent <Image>().color = Color.white;
            }
        }
        Player.instance.state.canMove = true;
        canProgressLevel = true;
    }
Esempio n. 6
0
    /// <summary>
    /// EndOfFrame後にコールバック処理する
    /// </summary>
    public static IEnumerator AddCallback(this WaitForEndOfFrame obj, Action callback)
    {
        yield return(obj);

        callback?.Invoke();
    }
Esempio n. 7
0
 public static AwaiterCoroutine <WaitForEndOfFrame> GetAwaiter(this WaitForEndOfFrame waitForEndOfFrame)
 {
     return(new AwaiterCoroutine <WaitForEndOfFrame>(waitForEndOfFrame));
 }
        private IEnumerator AwardCoinController(int t_CurrentLevel)
        {
            int t_ListOfCoin = m_CoinListReference.items.Length;
            List <GameObject> t_FilteredList = new List <GameObject>();

            for (int index = 0; index < t_ListOfCoin; index++)
            {
                if (m_CoinListReference.items[index].requiredLevel <= t_CurrentLevel)
                {
                    t_FilteredList.Add(m_CoinListReference.items[index].obstaclePrefab);
                }
            }

            WaitForEndOfFrame t_CycleDelay = new WaitForEndOfFrame();

            GameObject    t_CoinObject;
            CoinAttribute t_CoinAttributeReference;
            int           t_CoinValue;
            int           t_NumberOfCoinPerFrame = Mathf.CeilToInt(t_CurrentLevel / 5.0f);

            t_NumberOfCoinPerFrame = 1 + (t_NumberOfCoinPerFrame >= 20 ? 20 : t_NumberOfCoinPerFrame);
            long t_RemainingCoinToAward = m_AwardedCoinAmount;

            while (m_IsAlreadyAwardingCoin)
            {
                for (int coinLoopIndex = 0; coinLoopIndex < t_NumberOfCoinPerFrame; coinLoopIndex++)
                {
                    t_CoinObject = m_CoinListReference.GetObject(t_FilteredList);
                    if (t_CoinObject != null)
                    {
                        t_CoinAttributeReference = t_CoinObject.GetComponent <CoinAttribute>();
                        t_CoinValue = t_CoinAttributeReference.coinToBeAwarded;
                        if (t_RemainingCoinToAward >= t_CoinValue)
                        {
                            AddCoinToUser(t_CoinValue, t_CoinAttributeReference.particleColor);
                            t_RemainingCoinToAward -= t_CoinValue;
                        }
                    }
                    else
                    {
                        Debug.Log("###Found Null Coin To Reward");
                    }
                }

                //Discard any list item that cannot be meet the remaining coin
                bool t_HasCheckedFinished = false;
                while (!t_HasCheckedFinished)
                {
                    t_HasCheckedFinished = true;

                    for (int index = 0; index < t_FilteredList.Count; index++)
                    {
                        t_CoinAttributeReference = t_FilteredList[index].GetComponent <CoinAttribute>();
                        if (t_CoinAttributeReference.coinToBeAwarded > t_RemainingCoinToAward)
                        {
                            t_FilteredList.RemoveAt(index);
                            t_FilteredList.TrimExcess();
                            t_HasCheckedFinished = false;
                            break;
                        }
                    }

                    //Debug
                    //string t_RemainingCoin = "RemainingCoin : " + t_RemainingCoinToAward + ", ";
                    //for (int index = 0; index < t_FilteredList.Count; index++) {

                    //    t_RemainingCoin += t_FilteredList[index].name + ", ";
                    //}
                    //Debug.Log(t_RemainingCoin);
                }

                if (t_RemainingCoinToAward <= 0)
                {
                    break;
                }
                else
                {
                    yield return(t_CycleDelay);
                }
            }

            m_IsAlreadyAwardingCoin = false;

            if (m_OnRewardGivenComplete != null)
            {
                m_OnRewardGivenComplete.Invoke();
            }

            StopCoroutine(AwardCoinController(0));
        }
        private IEnumerator FadeOutCoroutine()
        {
            GameObject airPlaneCollider = GameObject.Find("Colliders");

            BoxCollider [] boxCollider = airPlaneCollider.GetComponentsInChildren <BoxCollider>();
            for (int i = 0; i < boxCollider.Length; i++)
            {
                boxCollider [i].enabled = false;
            }
            var   bloom           = GameObject.FindObjectOfType <BloomOptimized>();
            float targetIntensity = 2.3f;
            float targetThreshold = 0.4f;

            var  musicController = GameObject.FindObjectOfType <MusicController>();
            bool tweenMusic      = musicController != null && musicController.gameplay != null;

            var   wait           = new WaitForEndOfFrame();
            float tween          = 1f;
            float tweenSpeed     = 0.5f;
            float startTime      = Time.realtimeSinceStartup;
            float lastTime       = startTime;
            float deltaTime      = 0;
            float fixedDeltaTime = Time.fixedDeltaTime;

            while (tween > 0.1)
            {
                deltaTime = Time.realtimeSinceStartup - lastTime;
                lastTime  = Time.realtimeSinceStartup;

                if (bloom != null)
                {
                    bloom.intensity = Mathf.Lerp(bloom.intensity, targetIntensity, tweenSpeed * deltaTime);
                    bloom.threshold = Mathf.Lerp(bloom.threshold, targetThreshold, tweenSpeed * deltaTime);
                }

                if (tweenMusic)
                {
                    musicController.gameplay.volume = Mathf.Lerp(musicController.gameplay.volume,
                                                                 0f, tweenSpeed * deltaTime);
                }

                // Slow down.
                Time.timeScale      = Mathf.Lerp(Time.timeScale, 0f, tweenSpeed * deltaTime);
                Time.fixedDeltaTime = fixedDeltaTime * Time.timeScale;

                tween = Mathf.Lerp(tween, 0f, tweenSpeed * deltaTime);

                yield return(wait);
            }
            if (Application.loadedLevel == (Application.levelCount - 1))
            {
                musicController.gameplay.volume = 0;
                endMusic.GetComponent <AudioSource> ().enabled = true;
            }
            // Speed up again.
            Time.timeScale      = 1f;
            Time.fixedDeltaTime = fixedDeltaTime;

            SetLevelFinished(true);
            gameController.DisActiveButtonOnOver();
            //gameController.SetActiveButtonOnOver();
            //levelCompletedMenu.SetActive(true);
            // Register level complete.
            //if (Application.loadedLevelName == "Gameplay_1_Redo")
            //{
            //    ShowOverMenu();
            //}
            //else
            //{
            //    Invoke("ShowOverMenu", 8f);
            //}

            if (drama)
            {
                drama.SetActive(true);
                // GameObject.Find("ButtonPause").SetActive(false);
                GameObject.Find("PickupIcon").SetActive(false);
                GameObject.Find("FuelUIRect").SetActive(false);
                //GameObject.Find("Joystick").SetActive(false);
                //GameObject.Find("Acce").SetActive(false);
                GameObject.Find("LifeIcon").SetActive(false);
            }
            else
            {
                levelCompletedMenu.SetActive(true);
            }
            if (Application.loadedLevel != (Application.levelCount - 1))
            {
                Invoke("ShowOverMenu", 3f);
            }
        }
Esempio n. 10
0
        IEnumerator SmoothScrollProgressCoroutine(
            int itemIndex,
            float duration,
            float normalizedOffsetFromViewportStart  = 0f,
            float normalizedPositionOfItemPivotToUse = 0f,
            Func <float, bool> onProgress            = null)
        {
            double minContentVirtualInsetFromVPAllowed = -_InternalState.VirtualScrollableArea;

            if (minContentVirtualInsetFromVPAllowed >= 0d)
            {
                _SmoothScrollCoroutine = null;

                if (onProgress != null)
                {
                    onProgress(1f);
                }
                yield break;
            }

            var ignorOnScroll_lastValue = _SkipComputeVisibilityInUpdateOrOnScroll;

            _SkipComputeVisibilityInUpdateOrOnScroll = true;

            _Collocation.scrollRect.StopMovement();
            Canvas.ForceUpdateCanvases();

            Func <double> getTargetVrtInset = () =>
            {
                minContentVirtualInsetFromVPAllowed = -_InternalState.VirtualScrollableArea;

                return(ScrollToHelper_GetContentStartVirtualInsetFromViewportStart_Clamped(
                           minContentVirtualInsetFromVPAllowed,
                           itemIndex,
                           normalizedOffsetFromViewportStart,
                           normalizedPositionOfItemPivotToUse
                           ));
            };

            double initialVrtInsetFromParent = -1d, targetVrtInsetFromParent = -1d;
            bool   needToCalculateInitialInset = true, needToCalculateTargetInset = true, notCanceledByCaller = true;
            float  startTime = Time.time, elapsedTime;
            double progress, value;
            var    endOfFrame = new WaitForEndOfFrame();

            do
            {
                yield return(null);

                yield return(endOfFrame);

                elapsedTime = Time.time - startTime;
                if (elapsedTime >= duration)
                {
                    progress = 1d;
                }
                else
                {
                    progress = Math.Sin((elapsedTime / duration) * Math.PI / 2);
                }

                if (needToCalculateInitialInset)
                {
                    initialVrtInsetFromParent   = _InternalState.ContentPanelVirtualInsetFromViewportStart;
                    needToCalculateInitialInset = _Collocation.loopItems;
                }

                if (needToCalculateTargetInset || _InternalState.lastComputeVisibilityHadATwinPass)
                {
                    targetVrtInsetFromParent   = getTargetVrtInset();
                    needToCalculateTargetInset = _Collocation.loopItems || _InternalState.lastComputeVisibilityHadATwinPass;
                }
                value = initialVrtInsetFromParent * (1d - progress) + targetVrtInsetFromParent * progress;                 // Lerp for double

                if (Math.Abs(targetVrtInsetFromParent - value) < 1f)
                {
                    value    = targetVrtInsetFromParent;
                    progress = 1d;
                }

                if (value > 0d)
                {
                    progress = 1d;
                    value    = 0d;
                }
                else
                {
                    ScrollToHelper_SetContentVirtualInsetFromViewportStart(value, false);
                }
            }while (progress < 1d && (onProgress == null || (notCanceledByCaller = onProgress((float)progress))));

            if (notCanceledByCaller)
            {
                ScrollToHelper_SetContentVirtualInsetFromViewportStart(getTargetVrtInset(), false);

                ComputeVisibilityForCurrentPosition(false, true, false, -.1);
                ComputeVisibilityForCurrentPosition(true, true, false, +.1);

                _SmoothScrollCoroutine = null;

                if (onProgress != null)
                {
                    onProgress(1f);
                }
            }

            _SkipComputeVisibilityInUpdateOrOnScroll = ignorOnScroll_lastValue;
        }
Esempio n. 11
0
        private IEnumerator AddCoinToUserController()
        {
            Vector2 t_DeviceScreenSize = DeviceInfoManager.Instance.GetScaledValueForSprite(0.9f);

            t_DeviceScreenSize *= 0.4f;

            WaitForEndOfFrame t_CycleDelay = new WaitForEndOfFrame();

            CoinData t_CurrentCoinData;

            Vector2 t_CoinPosition;
            Vector2 t_SpawnPoint;
            float   t_CurrentTime;
            float   t_CoinSpawnTime = Time.time;

            while (m_CoinData.Count > 0)
            {
                t_CurrentCoinData = m_CoinData.Dequeue();

                if (t_CurrentCoinData.numberOfCoinToBeSpawned > 0)
                {
                    t_CurrentTime = Time.time;
                    if (t_CurrentTime > t_CurrentCoinData.timeForNextCoinSpawn)
                    {
                        t_CurrentCoinData.timeForNextCoinSpawn = t_CurrentTime + t_CurrentCoinData.coinSpawnDelay;
                        t_CoinPosition = new Vector2(
                            Random.Range(-t_DeviceScreenSize.x, t_DeviceScreenSize.x),
                            Random.Range(-t_DeviceScreenSize.y, t_DeviceScreenSize.y)
                            );

                        GameObject t_NewCoin = Instantiate(
                            coinPrefeb,
                            Vector3.zero,
                            Quaternion.identity
                            );

                        t_NewCoin.transform.parent = transform;
                        t_SpawnPoint = new Vector2(
                            Random.Range(0f, 1f) <= 0.5f ? Random.Range(t_CoinPosition.x, t_CoinPosition.x - spawnRadius) : Random.Range(t_CoinPosition.x, t_CoinPosition.x + spawnRadius),
                            Random.Range(0f, 1f) <= 0.5f ? Random.Range(t_CoinPosition.y, t_CoinPosition.y - spawnRadius) : Random.Range(t_CoinPosition.y, t_CoinPosition.y + spawnRadius)
                            );

                        t_NewCoin.GetComponent <CoinMovement>().StartCoinMovement(coinInfoParent, coinInfoPrefab, transform, t_SpawnPoint, t_CurrentCoinData.coinColor, t_CurrentCoinData.coinValue, false);
                        t_CurrentCoinData.numberOfCoinToBeSpawned--;
                    }
                }

                if (t_CurrentCoinData.numberOfCoinToBeSpawned > 0)
                {
                    m_CoinData.Enqueue(t_CurrentCoinData);
                }

                yield return(t_CycleDelay);
            }

            yield return(new WaitForSeconds(2f));

            //coinInfoParent.gameObject.SetActive(false);

            StopCoroutine(AddCoinToUserController());
        }
Esempio n. 12
0
 public override void OnStart()
 {
     nextFrame    = new WaitForEndOfFrame();
     baseRotation = transform.eulerAngles.y + 360;
 }
Esempio n. 13
0
    IEnumerator CheckTapInput()
    {
        var   touchDelay    = new WaitForEndOfFrame();// new WaitForSeconds(.15f);
        bool  shouldExecute = false;
        float cooldown      = 0.5f;
        int   tapCount      = 0;
        int   touches       = 0;
        int   marked        = 0;

        while (true)
        {
            shouldExecute = false;

            if (canTap && (Input.touchCount > 0 || Input.GetMouseButtonDown(0)))
            {
                if (Input.touchCount > 0)
                {
                    if (Input.touches[0].phase == TouchPhase.Began)
                    {
                        touches       = Input.touchCount;
                        shouldExecute = true;
                    }
                }
#if UNITY_EDITOR
                if (Input.GetMouseButtonDown(0))
                {
                    shouldExecute = true;
                    touches       = 1;
                }

                if (Input.GetKey(KeyCode.LeftShift))
                {
                    touches++;
                }
                if (Input.GetKey(KeyCode.LeftAlt))
                {
                    touches++;
                }
#endif
                if (shouldExecute)
                {
                    marked = touches;

                    if (cooldown > 0 && tapCount == 1)
                    {
                        //Has double tapped
                        TapDelegate(touches, 2);
                        marked   = 0;
                        tapCount = 0;
                        yield return(touchDelay);
                    }
                    else
                    {
                        cooldown  = 0.5f;
                        tapCount += 1;
                    }
                }
            }

            if (cooldown > 0)
            {
                cooldown -= 1f * Time.deltaTime;
            }
            else
            {
                tapCount = 0;

                if (tapCD > 0)
                {
                    tapCD -= 1f * Time.deltaTime;
                    //we swiped too recently, abort the tap
                    marked = 0;
                }
                else
                {
                    if (marked > 0)
                    {
                        TapDelegate(marked, 1);
                        yield return(touchDelay);
                    }
                    marked = 0;
                }
            }

            yield return(null);
        }
    }
Esempio n. 14
0
 private static IEnumerable YieldToEnumerable(WaitForEndOfFrame value)
 {
     yield return(value);
 }
Esempio n. 15
0
 public static YieldAwaiter <YieldInstruction> GetAwaiter(this WaitForEndOfFrame instruction)
 {
     return(new YieldAwaiter <YieldInstruction>(instruction));
 }
Esempio n. 16
0
    IEnumerator StartCoroutine()
    {
        Debug.Log(Environment.CurrentDirectory);
        Type entryType = Type.GetType("EntryEngine.Entry");

        if (entryType == null)
        {
            Loader loader = new Loader();
            if (Application.platform != RuntimePlatform.WindowsEditor && !string.IsNullOrEmpty(ServerUrl))
            //if (!string.IsNullOrEmpty(ServerUrl))
            {
                text = "正在检测版本更新";

                // 检查版本更新进行热更
                WaitForEndOfFrame wait    = new WaitForEndOfFrame();
                float             timeout = 0;
                WWW    www          = new WWW(ServerUrl + VERSION);
                byte[] versionBytes = null;
                while (true)
                {
                    if (www.isDone)
                    {
                        if (string.IsNullOrEmpty(www.error))
                        {
                            versionBytes = www.bytes;
                        }
                        else
                        {
                            text = "107:" + www.error;
                        }
                        break;
                    }
                    else
                    {
                        timeout += Time.deltaTime;
                        if (timeout >= 2)
                        {
                            // 下载超时
                            text = "下载超时,请检查网络后再试";
                            break;
                        }
                        yield return(wait);
                    }
                }
                //HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ServerUrl + VERSION);
                //request.Timeout = 5000;
                //request.ContentType = "application/x-www-form-urlencoded";
                //bool isDone = false;
                //request.BeginGetResponse((ar) =>
                //{
                //    try
                //    {
                //        var response = request.EndGetResponse(ar);
                //        versionBytes = new byte[8];
                //        response.GetResponseStream().Read(versionBytes, 0, 8);
                //        response.Close();
                //    }
                //    catch (Exception ex)
                //    {
                //        text = ex.Message;
                //    }
                //    isDone = true;
                //}, request);

                if (versionBytes != null)
                {
                    byte[] newVersionBytes = null;
                    if (!loader.Load(VERSION))
                    {
                        yield return(loader.www);
                    }
                    {
                        for (int i = 0; i < 8; i++)
                        {
                            if (loader.bytes[i] != versionBytes[i])
                            {
                                // 需要更新版本
                                newVersionBytes = versionBytes;
                                break;
                            }
                        }
                    }

                    if (newVersionBytes != null)
                    {
                        text = "正在计算更新包大小";

                        www = new WWW(ServerUrl + FILE_LIST);
                        yield return(www);

                        if (!string.IsNullOrEmpty(www.error))
                        {
                            text = "169:" + www.error;
                            yield break;
                        }

                        if (!loader.Load(FILE_LIST))
                        {
                            yield return(loader.www);
                        }
                        string[] oldList          = ReadString(loader.bytes).Split(SPLIT, StringSplitOptions.RemoveEmptyEntries);
                        byte[]   newFilelistBytes = www.bytes;
                        string[] newList          = ReadString(newFilelistBytes).Split(SPLIT, StringSplitOptions.RemoveEmptyEntries);

                        // 暂时不删除不需要了的文件,只列出需要下载的新文件或者需要更新的文件
                        Dictionary <string, Filelist> oldFilelist = new Dictionary <string, Filelist>();
                        foreach (var item in oldList)
                        {
                            string[] splits = item.Split('\t');
                            Filelist file   = new Filelist();
                            file.File   = splits[0];
                            file.Time   = splits[1];
                            file.Length = long.Parse(splits[2]);
                            oldFilelist.Add(splits[0], file);
                        }

                        List <Filelist> newFilelist = new List <Filelist>();
                        foreach (var item in newList)
                        {
                            string[] splits = item.Split('\t');
                            Filelist file;
                            if (oldFilelist.TryGetValue(splits[0], out file))
                            {
                                // 时间不一致需要更新
                                if (file.Time != splits[1])
                                {
                                    file.Length = long.Parse(splits[2]);
                                    newFilelist.Add(file);
                                }
                            }
                            else
                            {
                                // 需要下载的新文件
                                file        = new Filelist();
                                file.File   = splits[0];
                                file.Time   = splits[1];
                                file.Length = long.Parse(splits[2]);
                                newFilelist.Add(file);
                            }
                        }

                        // 可能只是删除了文件,导致没有需要更新的文件
                        if (newFilelist.Count > 0)
                        {
                            long needDownload = newFilelist.Sum(f => f.Length) >> 10;
                            long download     = 0;
                            text = string.Format("正在更新:{0}kb", needDownload);
                            foreach (var item in newFilelist)
                            {
                                www = new WWW(ServerUrl + item.File);
                                yield return(www);

                                if (!string.IsNullOrEmpty(www.error))
                                {
                                    text = string.Format("229: file: {0} error: {1} len: {2} text:{3}", item.File, www.error, item.File.Length, string.Join(",", item.File.Select(c => ((int)c).ToString()).ToArray()));
                                    yield break;
                                }

                                item.File = item.File.Replace('\\', '/');
                                string dir = Path.GetDirectoryName(item.File);
                                if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                                {
                                    Directory.CreateDirectory(dir);
                                }
                                File.WriteAllBytes(item.File, www.bytes);
                                // todo:每完成一个下载都写入旧文件列表,这样中途退出下次也能接着上次中断的文件开始下载
                                download += item.Length >> 10;
                                text      = string.Format("正在更新:{0}kb / {1}kb", download, needDownload);
                            }
                            File.WriteAllBytes(FILE_LIST, newFilelistBytes);
                        }

                        File.WriteAllBytes(VERSION, newVersionBytes);
                        Debug.Log("版本更新完成 {0}" + BitConverter.ToInt64(newVersionBytes, 0));
                    }
                }// end of if (www.error)
            }

            text = "正在准备运行环境";

            if (!loader.Load(RUNTIME))
            {
                yield return(loader.www);
            }
            {
                // 加载EntryEngine
                Assembly assembly = AppDomain.CurrentDomain.Load(loader.bytes, null);
                // 调用dll自解析
                Type       type   = assembly.GetType("Program");
                MethodInfo method = type.GetMethod("Main", BindingFlags.Public | BindingFlags.Static);
                method.Invoke(null, new object[1] {
                    null
                });
                Debug.Log("Load runtime completed.");
            }

            if (!loader.Load(FILE_LIST))
            {
                yield return(loader.www);
            }
            {
                string[] list = Encoding.UTF8.GetString(loader.bytes).Split(SPLIT, StringSplitOptions.RemoveEmptyEntries);
                // 从1开始,第0个元素是UnityRuntime.bytes
                for (int i = 1; i < list.Length; i++)
                {
                    string dllFile = list[i].Split('\t')[0];
                    if (!dllFile.EndsWith(".bytes"))
                    {
                        break;
                    }
                    if (!loader.Load(dllFile))
                    {
                        yield return(loader.www);
                    }
                    AppDomain.CurrentDomain.Load(loader.bytes, null);
                    Debug.Log(string.Format("加载{0}完成", dllFile));
                }
            }
        }

        text = "程序即将启动";

        // 创建Unity入口
        Assembly unity    = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == "Unity");
        Type     gateType = unity.GetType("EntryEngine.Unity.UnityGate");
        var      gate     = gameObject.AddComponent(gateType);

        // 设置同名属性
        //Debug.Log(gateType.GetProperty("Gate", BindingFlags.Public | BindingFlags.Static).GetValue(null, new object[0]));  // 测试是否已经执行了Start: 没有执行
        //var fields = GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
        //for (int i = 0; i < fields.Length; i++)
        //    gateType.GetField(fields[i].Name, BindingFlags.Public | BindingFlags.Static).SetValue(null, fields[i].GetValue(this));
        gateType.GetField("GLMaterial", BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance).SetValue(gate, GLMaterial);

        // 等待帧结束,让入口Start调用完毕
        yield return(new WaitForEndOfFrame());

        // 加载游戏入口场景
        Assembly client = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == "Client");
        // 使用入口展示场景实例 entry.ShowMainScene<T>();
        PropertyInfo entry = gateType.GetProperty("Entry");

        entry.PropertyType.GetMethod("ShowMainScene", Type.EmptyTypes).
        MakeGenericMethod(client.GetType("MAIN")).
        Invoke(entry.GetValue(gate, new object[0]), new object[0]);

        // 移除加载程序
        DestroyImmediate(this);
    }
Esempio n. 17
0
 void Awake()
 {
     TextColor         = myText.color;
     waitForEndOfFrame = new WaitForEndOfFrame();
     StartCoroutine(AlphaPingPong());
 }
    IEnumerator ClickedParts5(float duration, Vector3 end)
    {
        WaitForEndOfFrame wait = new WaitForEndOfFrame();

        Vector3 start   = m_btnPartsNew[4].gameObject.transform.localPosition;
        float   elapsed = 0.0f;

        while (elapsed < duration)
        {
            elapsed += Time.deltaTime;
            m_btnPartsNew[4].gameObject.transform.localPosition = Vector3.Lerp(start, end, elapsed / duration);
            yield return(wait);
        }

        m_btnPartsNew[4].gameObject.GetComponent <BoxCollider>().enabled = false;

        m_btnPartsNew[4].gameObject.transform.localPosition = end;

        if (m_btnPartsNew.Length == 5)
        {
            m_btnPartsNew[0].gameObject.SetActive(false);
            m_btnPartsNew[1].gameObject.SetActive(false);
            m_btnPartsNew[2].gameObject.SetActive(false);
            m_btnPartsNew[3].gameObject.SetActive(false);
        }

        else if (m_btnPartsNew.Length == 8)
        {
            m_btnPartsNew[0].gameObject.SetActive(false);
            m_btnPartsNew[1].gameObject.SetActive(false);
            m_btnPartsNew[2].gameObject.SetActive(false);
            m_btnPartsNew[3].gameObject.SetActive(false);
            m_btnPartsNew[5].gameObject.SetActive(false);
            m_btnPartsNew[6].gameObject.SetActive(false);
            m_btnPartsNew[7].gameObject.SetActive(false);
        }


        for (int i = 0; i < non_btns.Length; i++)
        {
            non_btns[i].gameObject.SetActive(false);
        }

        partsInfoSub.SetActive(true);


        if (_InfoSummaries.Length == 5)
        {
            _InfoSummaries[0].gameObject.SetActive(false);
            _InfoSummaries[1].gameObject.SetActive(false);
            _InfoSummaries[2].gameObject.SetActive(false);
            _InfoSummaries[3].gameObject.SetActive(false);
            _InfoSummaries[4].gameObject.SetActive(true);
        }

        else if (_InfoSummaries.Length == 8)
        {
            _InfoSummaries[0].gameObject.SetActive(false);
            _InfoSummaries[1].gameObject.SetActive(false);
            _InfoSummaries[2].gameObject.SetActive(false);
            _InfoSummaries[3].gameObject.SetActive(false);
            _InfoSummaries[4].gameObject.SetActive(true);
            _InfoSummaries[5].gameObject.SetActive(false);
            _InfoSummaries[6].gameObject.SetActive(false);
            _InfoSummaries[7].gameObject.SetActive(false);
        }
    }
Esempio n. 19
0
 static CoroutineEx()
 {
     CoroutineEx.WaitForEndOfFrame    = new WaitForEndOfFrame();
     CoroutineEx.WaitForSecondsBuffer = new Dictionary <float, WaitForSeconds>();
 }
Esempio n. 20
0
        private Sequence GameLoop()
        {
            m_Proxy.OnEnable();

            var now = System.DateTimeOffset.Now;

            m_Proxy.OnBeforeUpdate(now);
            InitGame();
            var sequence = Entry();

            m_Proxy.UpdateCurrentScene();
            UpdateGame();
            m_Proxy.DrawCurrentScene();
            DrawGame();

            var samplers = new[] {
                UnityEngine.Profiling.CustomSampler.Create("WaitForNextFrame"),
                UnityEngine.Profiling.CustomSampler.Create("Sleep"),
                UnityEngine.Profiling.CustomSampler.Create("BusyWait"),
                UnityEngine.Profiling.CustomSampler.Create("GameCanvas"),
                UnityEngine.Profiling.CustomSampler.Create("EngineUpdate"),
                UnityEngine.Profiling.CustomSampler.Create("UpdateGame"),
                UnityEngine.Profiling.CustomSampler.Create("Entry.MoveNext"),
                UnityEngine.Profiling.CustomSampler.Create("DrawGame")
            };
            var isRunning       = true;
            var targetFrameTime = System.DateTimeOffset.Now;
            var w4ef            = new WaitForEndOfFrame();

            while (enabled)
            {
                if (!m_Proxy.VSyncEnabled)
                {
                    //
                    // https://blogs.unity3d.com/jp/2019/06/03/precise-framerates-in-unity/
                    //
                    yield return(w4ef);

                    samplers[0].Begin();
                    {
                        targetFrameTime += System.TimeSpan.FromSeconds(m_Proxy.TargetFrameInterval);
                        now              = System.DateTimeOffset.Now;

                        var diff = (targetFrameTime - now).TotalMilliseconds;
                        if (diff > 0)
                        {
                            if (diff > 1)
                            {
                                samplers[1].Begin();
                                {
                                    var sleepTime = Mathf.Max(0, (int)(diff - 1));
                                    System.Threading.Thread.Sleep(sleepTime);
                                }
                                samplers[1].End();
                            }

                            samplers[2].Begin();
                            {
                                do
                                {
                                    now = System.DateTimeOffset.Now;
                                }while (now < targetFrameTime);
                            }
                            samplers[2].End();
                        }
                        else if (diff < 0)
                        {
                            targetFrameTime = now;
                        }
                    }
                    samplers[0].End();
                }

                yield return(null);

                samplers[3].Begin();
                {
                    samplers[4].Begin();
                    {
                        m_Proxy.OnBeforeUpdate(System.DateTimeOffset.Now);
                    }
                    samplers[4].End();

                    samplers[5].Begin();
                    {
                        m_Proxy.UpdateCurrentScene();
                        UpdateGame();
                    }
                    samplers[5].End();

                    samplers[6].Begin();
                    {
                        isRunning = isRunning && sequence.MoveNext();
                    }
                    samplers[6].End();

                    samplers[7].Begin();
                    {
                        m_Proxy.DrawCurrentScene();
                        DrawGame();
                        m_Proxy.OnAterDraw();
                    }
                    samplers[7].End();
                }
                samplers[3].End();
            }
        }
Esempio n. 21
0
 void Awake()
 {
     waitEndFrame = new WaitForEndOfFrame();
 }
Esempio n. 22
0
        private IEnumerator CoSteamNetworkingLoop()
        {
            var waitMode = new WaitForEndOfFrame();

            while (true)
            {
                uint     packetSize;
                CSteamID steamID;

                // Receive data packages (on channel 0)
                while (SteamNetworking.ReadP2PPacket(netBuffer, BufferLength, out packetSize, out steamID))
                {
                    if (packetSize == 0)
                    {
                        if (!isClientConnected && steamID == remoteSteamId)
                        {
                            isClientConnected = true;
                            client.connection.InvokeHandlerNoData(MsgType.Connect);
                        }
                    }
                    else
                    {
                        if (steamID == remoteSteamId)
                        {
                            client.connection.TransportReceive(netBuffer, (int)packetSize, 0);
                        }
                        else if (NetworkServer.active)
                        {
                            try
                            {
                                steamIdToConnection[steamID].TransportReceive(netBuffer, (int)packetSize, 0);
                            }
                            catch (KeyNotFoundException) { }
                        }
                    }
                }


                // Receive ping packages (on channel 1)
                var time = Time.realtimeSinceStartup;

                while (SteamNetworking.ReadP2PPacket(netBuffer, BufferLength, out packetSize, out steamID, 1))
                {
                    if (packetSize == sizeof(float))
                    {
                        if (steamID == remoteSteamId)
                        {
                            SteamNetworking.SendP2PPacket(steamID, netBuffer, sizeof(float), EP2PSend.k_EP2PSendUnreliableNoDelay, 1);
                        }
                        else if (NetworkServer.active)
                        {
                            int rtt = Mathf.RoundToInt((time - System.BitConverter.ToSingle(netBuffer, 0)) * 1000);

                            try
                            {
                                (steamIdToConnection[steamID] as SteamNetConnection).rtt = rtt;
                            }
                            catch (KeyNotFoundException) { }
                        }
                    }
                }

                if (isClientConnected)
                {
                    client.connection.FlushChannels();
                }

                yield return(waitMode);
            }
        }
Esempio n. 23
0
    private IEnumerator CycleBoard()
    {
        _cycling = true;

        Debug.Log("CYCLING");

        WaitForEndOfFrame frameWait    = new WaitForEndOfFrame();
        WaitForSeconds    secondsWait1 = new WaitForSeconds(1);
        WaitForSeconds    secondsWait2 = new WaitForSeconds(2);

        bool level = _currentLevel >= _maxLevels;

        Vector3 position = Vector3.zero;

        position.y = 5.5f;

        Vector3 bigPosition = Vector3.zero;

        bigPosition.y = -5.5f;

        _chanimation.MagicNumber = 1;

        _bigText.text    = "Congratulations!";
        _bigTextSub.text = level ? "You completed the game!" : "You cleared level " + (_currentLevel).ToString();

        _systemBoard.Play();

        for (float t = 0; t < 1f; t += Time.deltaTime)
        {
            _boardForm.position   = Vector3.Lerp(_boardForm.position, position, t * t);
            _bigTextForm.position = Vector3.Lerp(bigPosition, Vector3.zero, Mathf.Sin(t * Mathf.PI * 0.5f));
            yield return(frameWait);
        }

        _systemBoard.Stop();

        if (!level)
        {
            _chanimation.MagicNumber = 7;

            yield return(secondsWait1);

            _chanimation.MagicNumber = 0;

            position.y = -5.5f;

            _boardForm.position = Vector3.zero;

            bool cool = _currentLevel % ((float)_maxLevels / 10f) == 0;

            if (cool && _boardSize < 5)
            {
                ++_boardSize;
            }

            SetupBoard(size: _boardSize, reset: false);

            bigPosition.y = 5.5f;

            for (float t = 0; t < 1f; t += Time.deltaTime)
            {
                _boardForm.position   = Vector3.Lerp(position, Vector3.zero, Mathf.Sin(t * Mathf.PI * 0.5f));
                _bigTextForm.position = Vector3.Lerp(_bigTextForm.position, bigPosition, t * t);
                yield return(frameWait);
            }

            _bigText.text = _bigTextSub.text = null;

            ++_currentLevel;
            _level.text = _currentLevel.ToString();

            _checkPointed = cool;

            if (_checkPointed)
            {
                _checkPointLevel = _currentLevel;
                _checkPointer.SetActive(true);
                _checkPointer.transform.GetChild(0).GetComponent <TextMesh>().text = _checkPointLevel.ToString();
            }
        }
        else
        {
            GameOver(true);
        }

        Debug.Log("CYCLING ENDED");

        _cycling = false;
    }
Esempio n. 24
0
	/*
	 * Simple screennshot example in the main thread
	 * Could be called as StartCoroutine(TakeScreenShotSimple())
	 */
	public IEnumerator TakeScreenShotSimple(Camera camera)
	{
		Debug.Log ("Screenshot Recording Single Thread -- STARTED");

		WaitForEndOfFrame waitForFrame = new WaitForEndOfFrame();

		while (true)
		{
			//Wait for frame
			yield return waitForFrame;

			if (frameNumber <= maxFrames && !saving)
			{
				saving = true;
				frameNumber++;

				tempRenderTexture = RenderTexture.active;
				RenderTexture.active = camera.targetTexture;
				camera.Render();

				//Debug.Log("CAMERA TARGET TEXTURE WIDTH: " + camera.targetTexture.width);
				//Debug.Log("CAMERA TARGET TEXTURE HEIGHT: " + camera.targetTexture.height);

				tempTexture2D = new Texture2D(camera.targetTexture.width, camera.targetTexture.height, TextureFormat.RGB24, false);
				tempTexture2D.ReadPixels(new Rect(0, 0, camera.targetTexture.width, camera.targetTexture.height), 0, 0);
				tempTexture2D.Apply();

				RenderTexture.active = tempRenderTexture;
				
				Color[] pix = tempTexture2D.GetPixels(100, 100, 1, 1);

				Debug.Log(pix[0].ToString());

				// Encode texture into JPG
				byte[] bytes = tempTexture2D.EncodeToJPG();

				Debug.Log("IMG " + frameNumber + " byte count: " + bytes.Length);

				var resultNumber = frameNumber.ToString().PadLeft(4, '0');

				// save in memory
				string filename = resultNumber + ".jpg";
				var path = persistentDataPath + "/" + filename;
				File.WriteAllBytes(path, bytes);

				Debug.Log ("Frame " + frameNumber);

				// don't wait for next frame to stop recording audio
				if (frameNumber >= maxFrames){
					audioRecorder.StopWriting();
				}

				saving = false;
			}
			else if (frameNumber > maxFrames && !saving) {
				// sync IndexedDB (browser)
				#if UNITY_WEBGL
					// Flush database in the web build
					Application.ExternalEval("_JS_FileSystem_Sync();");
					// Handle database
					Application.ExternalEval("handleDatabase();");
				#endif

				Debug.Log ("SCREENRECORDER FINISHED");

				break;
			}
		}
	}
Esempio n. 25
0
 private void Awake()
 {
     _eof = new WaitForEndOfFrame();
 }
Esempio n. 26
0
	// Multithread example (tested in standalone builds)
	public IEnumerator TakeScreenShot(Camera camera)
	{
		Debug.Log ("Screenshot recording Multi-thread -- STARTED");
		WaitForEndOfFrame waitForFrame = new WaitForEndOfFrame();

		while (true)
		{
			//Wait for frame
			yield return waitForFrame;

			if (frameNumber <= maxFrames)
			{
				// Calculate number of video frames to produce from this game frame
				// Generate 'padding' frames if desired framerate is higher than actual framerate
				float thisFrameTime = Time.time;
				int framesToCapture = ((int)(thisFrameTime / captureFrameTime)) - ((int)(lastFrameTime / captureFrameTime));

				// Capture the frame
				if(framesToCapture > 0)
				{
					RenderTexture.active = camera.targetTexture;
					camera.Render();
					
					tempTexture2D = new Texture2D(camera.targetTexture.width, camera.targetTexture.height,
						TextureFormat.RGB24, false);
					tempTexture2D.ReadPixels(new Rect(0, 0, camera.targetTexture.width, camera.targetTexture.height), 0, 0);
					tempTexture2D.Apply();
					// SERVER: we could send the texture here to a server, which then renders all images to a video (e.g., mp4)
					RenderTexture.active = null;
				}
				// Add the required number of copies to the queue
				for(int i = 0; i < framesToCapture && frameNumber <= maxFrames; ++i)
				{
					frameQueue.Enqueue(tempTexture2D.GetRawTextureData());

					frameNumber++;

					if(frameNumber % frameRate == 0)
					{
						Debug.Log ("Frame " + frameNumber);
					}
				}

				// don't wait for next frame to stop recording audio
				if (frameNumber >= maxFrames){
					audioRecorder.StopWriting();
				}
				
				lastFrameTime = thisFrameTime;
			}
			else //keep making screenshots until it reaches the max frame amount
			{
				// Inform thread to terminate when finished processing frames
				terminateThreadWhenDone = true;

				// Disable script
				//this.enabled = false;
				StopMainTasks();
				break;
			}
		}
		
    }
Esempio n. 27
0
    private IEnumerator RenderLoop()
    {
        if (cachedWaitForEndOfFrame == null)
        {
            cachedWaitForEndOfFrame = new WaitForEndOfFrame();
        }
        yield return(cachedWaitForEndOfFrame);

        yield return(cachedWaitForEndOfFrame);

        if (isInitializeGraphic == false)
        {
            InitializeGraphic();
            // sync here to wait InitializeGraphic done because InitializeGraphic is migration to render thread.
            synchronizer.sync();
            textureManager      = new TextureManager();
            isInitializeGraphic = true;
        }

        Log.d(LOG_TAG, "RenderLoop() is started");
        var tim = Time.realtimeSinceStartup;

#if UNITY_EDITOR
        if (!Application.isEditor)
#endif
        {
            WaveVR_Utils.WVR_SetPerformanceLevels(cpuPerfLevel, gpuPerfLevel);
            Log.i(LOG_TAG, "SetPerformanceLevels cpuPerfLevel " + cpuPerfLevel + " gpuPerfLevel " + gpuPerfLevel);
            // Restart ATW thread before rendering.
            while (!WaveVR_Utils.WVR_IsATWActive())
            {
                yield return(cachedWaitForEndOfFrame);

                if (surfaceChanged && isNeedTimeout == false)
                {
                    break;
                }
                if (Time.realtimeSinceStartup - tim > 1.0f)
                {
                    Log.w(LOG_TAG, "Waiting for surface change is timeout.");
                    break;
                }
            }
            // Reset isNeedTimeout flag
            isNeedTimeout = false;

            if (textureManager != null)
            {
                if (!textureManager.validate())
                {
                    textureManager.reset();
                }
            }
        }
        Log.d(LOG_TAG, "First frame");
        WaveVR_Utils.IssueEngineEvent(WaveVR_Utils.EngineEventID.FIRST_FRAME);

        setLoadingCanvas(false);
        Log.d(LOG_TAG, "RenderLoop() is running");

        while (true)
        {
            Log.gpl.d(LOG_TAG, "RenderLoop() is still running");
            WaveVR_Utils.Trace.BeginSection("RenderLoop", false);
#if UNITY_EDITOR
            if (Application.isEditor)
            {
                if (WaveVR.Instance.isSimulatorOn)
                {
                    WaveVR.Instance.UpdatePoses(origin, true);
                }
                else
                {
                    WaveVR_Utils.Event.Send(WaveVR_Utils.Event.NEW_POSES, new WVR_DevicePosePair_t[0], new WaveVR_Utils.RigidTransform[0]);
                    WaveVR_Utils.Event.Send(WaveVR_Utils.Event.AFTER_NEW_POSES);
                }
                if (textureManager != null)
                {
                    textureManager.Next();
                }
            }
            else
#endif
            {
                WaveVR.Instance.UpdatePoses(origin);
                // Set next texture before running any graphic command.
                if (textureManager != null)
                {
                    textureManager.Next();
                }
            }

            if (configurationChanged)
            {
                WaveVR_Render.Expand(this);
                configurationChanged = false;
            }

            RenderEye(lefteye.getCamera(), WVR_Eye.WVR_Eye_Left);
            RenderEye(righteye.getCamera(), WVR_Eye.WVR_Eye_Right);
            WaveVR_Utils.Trace.EndSection(false);

            // Put here to control the time of next frame.
            TimeControl();

            Log.gpl.d(LOG_TAG, "End of frame");
            yield return(cachedWaitForEndOfFrame);
        }
    }
 // Start is called before the first frame update
 void Start()
 {
     frameBreak = new WaitForEndOfFrame();
     _detector  = GetComponent <ObjectDetectionInference>();
     httpLoader = GetComponent <HttpImageLoading>();
 }
Esempio n. 29
0
        private IEnumerator Start()
        {
            // only one can exist in scene at a time
            if (singleton != null)
            {
                disposeAPI = false;// don't dispose apis if we're not the owner of possible native instances
                Destroy(gameObject);
                yield break;
            }
            DontDestroyOnLoad(gameObject);
            singleton = this;

            // print version
            Debug.Log("XRInput version: 1.0.6");

            // wait for XR loader
            while (loader == null || !XRSettings.enabled)
            {
                try
                {
                    if (loaderOverride != null)
                    {
                        loader = loaderOverride;
                    }
                    else
                    {
                        loader = XRGeneralSettings.Instance.Manager.activeLoader;
                    }
                }
                catch { }
                yield return(new WaitForSeconds(1));
            }

            // give XR some time to start
            var wait = new WaitForEndOfFrame();

            yield return(wait);

            yield return(wait);

            yield return(wait);

            yield return(wait);

            yield return(wait);

            yield return(new WaitForSeconds(1));

            try
            {
                // init controller instance IDs
                for (int i = 0; i != state_controllers.Length; ++i)
                {
                    state_controllers[i].id = Guid.NewGuid();
                }

                // get loader type
                var    loaderType     = loader.GetType();
                string loaderTypeName = loaderType.Name;
                Debug.Log($"XR-Loader: '{loader.name}' TYPE:{loaderType}");

                // auto set rumble channel
                if (autoSetRumbleChannel)
                {
                    if (loaderTypeName == "OpenXRLoader")
                    {
                        rumbleChannel = 1;
                    }
                    else
                    {
                        rumbleChannel = 0;
                    }
                }

                // auto detect
                if (apiType == XRInputAPIType.AutoDetect)
                {
                    #if UNITY_STANDALONE
                    if (loaderTypeName == "OpenVRLoader")
                    {
                        apiType = XRInputAPIType.OpenVR;
                    }
                    else
                    {
                        apiType = XRInputAPIType.UnityEngine_XR;
                    }
                    #else
                    apiType = XRInputAPIType.UnityEngine_XR;
                    #endif
                }

                // init api
                disposeAPI = true;
                switch (apiType)
                {
                case XRInputAPIType.UnityEngine_XR: api = new UnityEngine_XR(); break;

                case XRInputAPIType.OpenVR: api = new OpenVR_New(); break;

                case XRInputAPIType.OpenVR_Legacy: api = new OpenVR_Legacy(); break;

                default: throw new NotImplementedException();
                }

                api.Init();

                // ensure we dispose before stopping to avoid editor race-condition bugs
                #if UNITY_EDITOR
                UnityEditor.EditorApplication.playModeStateChanged += EditorApplication_playModeStateChanged;
                #endif
            }
            catch (Exception e)
            {
                if (InitializedCallback != null)
                {
                    InitializedCallback(false);
                }
                throw e;
            }

            if (InitializedCallback != null)
            {
                InitializedCallback(true);
            }
        }
Esempio n. 30
0
        private IEnumerator UnzipFileHandler(Queue <string> queue, string bundDataTime, Callback callback)
        {
            ZipInputStream    zipInputStream = null;
            ZipEntry          zipEntry       = null;
            WaitForEndOfFrame waitFrame      = new WaitForEndOfFrame();
            Thread            unzipThread    = new Thread(new ParameterizedThreadStart(UnzipFileThread));
            int delatime = (int)(Time.deltaTime * 1000);

            unzipThread.Start(delatime);

            while (queue.Count != 0)
            {
                string localUrl = queue.Dequeue();
                WWW    www      = new WWW(localUrl);
                yield return(www);

                if (!string.IsNullOrEmpty(www.error))
                {
                    //DebugUtils.LogError( DebugUtils.Type.AssetBundle, string.Format( "Loading zip file failed! when decompress zip! err: {0}  url = {1}", www.error, localUrl ) );
                    www.Dispose();
                    www = null;
                    continue;
                }

                zipInputStream          = new ZipInputStream(new MemoryStream(www.bytes, 0, www.bytes.Length), true);
                zipInputStream.Password = "******";
                while ((zipEntry = zipInputStream.GetNextEntry()) != null)
                {
                    curUnZipData            = new UnZipData();
                    curUnZipData.sourcePath = localUrl;
                    curUnZipData.targetPath = assetPath + zipEntry.FileName;
                    curUnZipData.stream     = zipInputStream;
                    unzipComplete           = true;

                    while (unzipComplete)
                    {
                        yield return(waitFrame);
                    }
                }

                www.Dispose();
                www = null;
            }

            DebugUtils.Log(DebugUtils.Type.AssetBundle, "unzip all files complete!");

            RemoveLocalZipListFile();
            unzipThread.Abort();
            unzipThread = null;
            using (FileStream fs = new FileStream(zipAssetPath + cacheDataTimeTxt, FileMode.OpenOrCreate))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.WriteLine(bundDataTime);
                    sw.Close();
                    sw.Dispose();
                }
                fs.Close();
                fs.Dispose();
            }
            System.GC.Collect();

            if (callback != null)
            {
                callback();
            }
        }