示例#1
0
    /// <summary>
    /// 给WWW 添加超时判断
    /// </summary>
    /// <param name="www"></param>
    /// <param name="onTimeOutAction"></param>
    /// <param name="result"> 该www访问的结果</param>
    /// <param name="TimeOut"></param>
    /// <returns></returns>
    public static IEnumerator CheckTimeOut(WWW www, System.Action onTimeOutAction, CoroutineResult result = null, float TimeOut = 20f)
    {
        if (result != null)
        {
            result.error = null;
        }
        float curTime         = 0;
        bool  is_www_disposed = false;

        if (www == null)
        {
            yield break;
        }

        //出错方法
        System.Action <string> onError = (errorStr) =>
        {
            if (string.IsNullOrEmpty(errorStr))
            {
                return;
            }
            if (result != null)
            {
                result.error      = errorStr;
                result._wwwResult = null;
            }
            if (!is_www_disposed)
            {
                www.DisposeAsync();                  //释放www
            }
        };

        System.Func <bool> www_isDone_func = () =>
        {
            try
            {
                return(www.isDone);
            }
            catch (Exception e)
            {
                if (Constants.isEditor)
                {
                    Debug.Log("<color=red>www_isDone_func : " + e.Message + "</color>");
                }
                is_www_disposed = true;
                onError("www has been disposed");
                return(false);
            }
        };

        //超时判断
        while (!www_isDone_func() && !is_www_disposed)
        {
            curTime += Time.deltaTime;
            if (curTime > TimeOut)
            {
                onError("TimeOut");
                if (onTimeOutAction != null)
                {
                    onTimeOutAction();
                }
                yield break;
            }

            yield return(0);
        }

        //www访问出错判断
        if (!is_www_disposed)
        {
            onError(www.error);
        }
    }