Exemplo n.º 1
0
    //public void LoadFromLocal()
    //{
    //    string path = "";

    //    path = "file://" + Application.persistentDataPath + "/ar-exp-saltbrochure-android";
    //    //path = "file://" + "C:/Users/sricciardi/Desktop/Projects/AR Projects/Salt-Generic-AR-App/Assets/AssetBundles/Android" + "/ar-exp-saltbrochure-android";
    //    Debug.Log(path);

    //    StartCoroutine(LoadFromMemoryAsync(path));
    //}


    IEnumerator DownloadAndCacheAB(string bundleURLPath, string manifestURLBundlePath)
    {
        //AssetBundle manifestBundle = AssetBundle.LoadFromFile(manifestBundlePath);
        //AssetBundleManifest manifest = manifestBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
        string editorManifestFilePath = Application.dataPath + "/AssetBundles/Android/" + ABFileName + ".manifest";
        string manifestFilePath       = Path.Combine(Application.persistentDataPath, ABmanifestFileName);
        string bundleFilePath         = Path.Combine(Application.persistentDataPath, ABFileName);

        Debug.Log("Unity Editor manifest path " + editorManifestFilePath);

        if (Application.isEditor)
        {
            DHmanifest = new DownloadHandlerFile(editorManifestFilePath);
            Debug.Log("I am running in the Unity Editor!");
        }
        else
        {
            DHmanifest = new DownloadHandlerFile(manifestFilePath);
        }

        //DownloadHandlerFile dh = new DownloadHandlerFile(filePath);
        //DownloadHandlerAssetBundle DHAB = new DownloadHandlerAssetBundle(bundleFilePath);

        //DownloadHandler DHmanifest = new DownloadHandlerFile(manifestFilePath);   // Correct!

        UWRmanifest = UnityWebRequest.Get(manifestURLBundlePath);
        //UWRbundle = UnityWebRequestAssetBundle.GetAssetBundle(bundleURLPath);
        //uwr.downloadHandler = dhAB;
        UWRmanifest.downloadHandler = DHmanifest;
        yield return(UWRmanifest.SendWebRequest());

        //UWRbundle.downloadHandler = DHAB;
        //yield return UWRbundle.SendWebRequest();

        //uwr.downloadHandler = dh;
        //yield return uwr.SendWebRequest();

        if (UWRmanifest.isNetworkError || UWRmanifest.isHttpError)
        {
            Debug.Log("Network error trying to retrieve the manifest file!");
        }
        else
        {
            Debug.Log("There was no Network error, so try to load the Asset Bundle from the local file");
            AssetBundle         manifestBundle = AssetBundle.LoadFromFile(manifestFilePath);
            AssetBundleManifest manifest       = manifestBundle.LoadAsset <AssetBundleManifest>("AssetBundleManifest");

            //Create new cache
            string today = DateTime.Today.ToLongDateString();
            Directory.CreateDirectory(today);
            Cache newCache = Caching.AddCache(today);

            //Set current cache for writing to the new cache if the cache is valid
            if (newCache.valid)
            {
                Caching.currentCacheForWriting = newCache;
            }

            //Download the bundle
            Hash128         hash             = manifest.GetAssetBundleHash(ABFileName);
            UnityWebRequest UWRbundleRequest = UnityWebRequestAssetBundle.GetAssetBundle(bundleURLPath, hash, 0);
            yield return(UWRbundleRequest.SendWebRequest());

            AssetBundle UWRbundle = DownloadHandlerAssetBundle.GetContent(UWRbundleRequest);

            //Get all the cached versions
            List <Hash128> listOfCachedVersions = new List <Hash128>();
            Caching.GetCachedVersions(UWRbundle.name, listOfCachedVersions);

            if (!AssetBundleContainsAssetIWantToLoad(UWRbundle))
            {
                Caching.currentCacheForWriting = Caching.GetCacheAt(Caching.cacheCount);
                Caching.RemoveCache(newCache);
                Debug.Log("There is no Scene in the downloaded Asset Bundle.");

                for (int i = listOfCachedVersions.Count - 1; i > 0; i--)
                {
                    //Load a different bundle from a different cache.
                    UWRbundleRequest = UnityWebRequestAssetBundle.GetAssetBundle(bundleURLPath, listOfCachedVersions[i], 0);
                    yield return(UWRbundleRequest.SendWebRequest());

                    UWRbundle = DownloadHandlerAssetBundle.GetContent(UWRbundleRequest);

                    //Check and see if the newly loaded bundle from the cache meets your criteria.
                    if (AssetBundleContainsAssetIWantToLoad(UWRbundle))
                    {
                        //This is where I need to load the scene the correct way.
                        break;
                    }
                }
            }
            else
            {
                Debug.Log("I found the scene I am looking for in the downloaded version.");
            }
        }



        /*
         * if (uwr.isNetworkError || uwr.isHttpError)
         * {
         *  Debug.Log(uwr.error);
         * } else
         * {
         *  //Get Asset Bundle
         *  AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(uwr);
         *
         *  isLoading = true;
         *
         *  if (uwr.isDone)
         *  {
         *
         *      //AssetBundleManifest manifest = bundle.LoadAsset<AssetBundleManifest>(bundle.name);
         *      Debug.Log("bundle name " + bundle.name);
         *      Debug.Log("is Streamed Asset Bundle " + bundle.isStreamedSceneAssetBundle);
         *  }
         *
         *
         *  //AssetBundle manifestBundle = AssetBundle.LoadFromFile(manifestBundlePath);
         *  //AssetBundleManifest manifest = bundle.LoadAssetAsync<AssetBundleManifest>(ABFileName);
         *  //Debug.Log("manifest " + manifest);
         *
         *  string[] assetBundlePaths = bundle.GetAllScenePaths();
         *
         *  if (assetBundlePaths != null) {
         *
         *      //AssetBundleLoadOperation request = AssetBundleManager.LoadLevelAsync(sceneAssetBundle, levelName, isAdditive);
         *      //if (request == null)
         *      //    yield break;
         *      //yield return StartCoroutine(request);
         *
         *      for (int i = 0; i < assetBundlePaths.Length; i++)
         *      {
         *          Debug.Log("string # " + i + " is " + assetBundlePaths[i]);
         *      }
         *  }
         */



        //string filePath = Path.Combine(Application.persistentDataPath, ABFileName);

        //DownloadHandlerFile dh = new DownloadHandlerFile(filePath);

        //UnityWebRequest requestFile = UnityWebRequest.Get(url);

        //requestFile.downloadHandler = dh;


        //yield return requestFile.SendWebRequest();

        //if (!requestFile.isHttpError && !requestFile.isNetworkError)
        //{
        //    Debug.Log("Download complete, attempting to load bundle.");

        //    AssetBundle bundleFile = AssetBundle.LoadFromFile(filePath);

        //    SceneManager.LoadScene(bundleFile.GetAllScenePaths()[0]);
        //}
        //else
        //{
        //    Debug.LogError(requestFile.responseCode + ": " + requestFile.error);
        //}



        // Load level from assetBundle.



        ////AssetBundleRequest asset = bundle.LoadAssetAsync<AssetBundleManifest>(ABFileName);
        //AssetBundleRequest asset = bundle.LoadAsset<AssetBundleManifest>(ABFileName);
        //yield return asset;

        ////Get the Asset Bundle Manifest
        //AssetBundleManifest loadedAssetMf = asset.asset as AssetBundleManifest;
        ////Get Hash128 from the AssetBundleManifest
        //Hash128 tempHash128 = loadedAssetMf.GetAssetBundleHash(ABFileName);

        ////Pass to the isVersionCached function
        //if (Caching.IsVersionCached(bundlePath, tempHash128))
        //{
        //    isCached = true;
        //    Debug.Log("Bundle is Cached");
        //} else
        //{
        //    isLoading = true;
        //    Debug.Log("Bundle is Downloading....");
        //}
        ////Caching.IsVersionCached(bundlePath, tempHash128);
    }
Exemplo n.º 2
0
    IEnumerator GetText()
    {
        UnityWebRequest request = UnityWebRequest.Get("http://koke.link:3000/unity/muse_SR_UR");

        // 下記でも可
        // UnityWebRequest request = new UnityWebRequest("http://example.com");
        // methodプロパティにメソッドを渡すことで任意のメソッドを利用できるようになった
        // request.method = UnityWebRequest.kHttpVerbGET;

        // リクエスト送信
        yield return(request.Send());

        // 通信エラーチェック
        if (request.isError)
        {
            Debug.Log(request.error);
        }
        else
        {
            if (request.responseCode == 200)
            {
                // UTF8文字列として取得する
                string httptext = request.downloadHandler.text;
                Debug.Log(httptext);

                membersInfo = JsonHelper.FromJson <membersinfo>(httptext);
                Debug.Log(membersInfo [10].info);



                int member_id = 10;
                for (int i = 0; i < 11; ++i)
                {
                    if (membersInfo[i].name == "穂乃果")
                    {
                        member_id = 0;
                    }
                    else if (membersInfo[i].name == "絵里")
                    {
                        member_id = 1;
                    }
                    else if (membersInfo[i].name == "ことり")
                    {
                        member_id = 2;
                    }
                    else if (membersInfo[i].name == "海未")
                    {
                        member_id = 3;
                    }
                    else if (membersInfo[i].name == "凛")
                    {
                        member_id = 4;
                    }
                    else if (membersInfo[i].name == "真姫")
                    {
                        member_id = 5;
                    }
                    else if (membersInfo[i].name == "希")
                    {
                        member_id = 6;
                    }
                    else if (membersInfo[i].name == "花陽")
                    {
                        member_id = 7;
                    }
                    else if (membersInfo[i].name == "にこ")
                    {
                        member_id = 8;
                    }

                    string rarity_str = "";
                    if (membersInfo[i].rarity == "4")
                    {
                        rarity_str = "UR";
                    }
                    else if (membersInfo[i].rarity == "3")
                    {
                        rarity_str = "SSR";
                    }
                    else if (membersInfo[i].rarity == "2")
                    {
                        rarity_str = "SR";
                    }
                    else if (membersInfo[i].rarity == "1")
                    {
                        rarity_str = "R";
                    }

                    /* ガチャ結果をGUI反映 */


                    GameObject.Find("Member_Gatcha" + i).GetComponent <Transform>().localScale = new Vector3(1, 1, 0);


                    // 特定素材がある場合はそれをload
                    GameObject.Find("Member_Gatcha" + i).GetComponent <Image>().sprite = Resources.Load <Sprite>("character/" + membersInfo[i].id);
                    if (GameObject.Find("Member_Gatcha" + i).GetComponent <Image>().sprite == null)
                    {
                        // 各レアリティ素材がある場合はそれをload
                        GameObject.Find("Member_Gatcha" + i).GetComponent <Image>().sprite = Resources.Load <Sprite>("character/muse0" + (member_id + 1) + "-" + rarity_str);
                        if (GameObject.Find("Member_Gatcha" + i).GetComponent <Image>().sprite == null)
                        {
                            // 素材がない場合は汎用R素材をload
                            GameObject.Find("Member_Gatcha" + i).GetComponent <Image>().sprite = Resources.Load <Sprite>("character/muse0" + (member_id + 1) + "-R");
                        }
                    }

                    //GameObject.Find("Button_Select_Member0").GetComponent<SpriteRenderer>().sprite = GameObject.Find("gatcha_member (" + i + ")").GetComponent<SpriteRenderer>().sprite;


                    //GameObject.Find("Text (" + i + ")").GetComponent<Text>().text = membersInfo[i].series;
                    GameObject.Find("Envelope_member" + i).GetComponent <Image>().sprite = envelopeIcon[Int32.Parse(membersInfo[i].rarity)];


                    /* 各ガチャ結果をインスタンスに代入 */

                    if (GameObject.Find("Button_Selected_MemberRoom_" + membersInfo[i].id))
                    {
                        Debug.Log("Found");
                        MemberRoom_Member memberObj = GameObject.Find("Button_Selected_MemberRoom_" + membersInfo[i].id).GetComponent <MemberRoom_Member>();
                        memberObj.id           = membersInfo[i].id;
                        memberObj.rarity       = membersInfo[i].rarity;
                        memberObj.name         = membersInfo[i].name;
                        memberObj.series       = membersInfo[i].series;
                        memberObj.fullimgurl_0 = membersInfo[i].fullimgurl_0;
                        memberObj.fullimgurl_1 = membersInfo[i].fullimgurl_1;
                        memberObj.info         = membersInfo[i].info;
                        memberObj.status_s     = membersInfo[i].status_s;
                        memberObj.status_p     = membersInfo[i].status_p;
                        memberObj.status_c     = membersInfo[i].status_c;
                        memberObj.type         = membersInfo[i].type;

                        memberObj.possesion = true;
                        GameObject.Find("Button_Selected_MemberRoom_" + membersInfo[i].id).transform.parent.gameObject.transform.parent.gameObject.GetComponent <Button_MemberRoom>().possesion = true;
                    }

                    Debug.Log(i + " " + membersInfo[i].id + " " + membersInfo[i].rarity + "" + membersInfo[i].name + "(" + membersInfo[i].series + "):" + membersInfo[i].type + "," + membersInfo[i].status_s + "," + membersInfo[i].status_p + "," + membersInfo[i].status_c);
                }
            }
        }
    }
Exemplo n.º 3
0
        private void UpdateSettings(BuildTarget currentBuildTarget)
        {
            if (currentBuildTarget != BuildTarget.WSAPlayer)
            {
                return;
            }

            EditorUserBuildSettings.wsaUWPBuildType = Values[ProjectSetting.WsaUwpBuildToD3D]
                ? WSAUWPBuildType.D3D
                : WSAUWPBuildType.XAML;

            if (Values[ProjectSetting.WsaFastestQuality])
            {
                for (var i = 0; i < QualitySettings.names.Length; i++)
                {
                    QualitySettings.DecreaseLevel(true);
                }

                int currentQualityLevel = QualitySettings.GetQualityLevel();

                // HACK: Edits QualitySettings.asset Directly
                // TODO: replace with friendlier version that uses built in APIs when Unity fixes or makes available.
                // See: http://answers.unity3d.com/questions/886160/how-do-i-change-qualitysetting-for-my-platform-fro.html
                try
                {
                    // Find the WSA element under the platform quality list and replace it's value with the current level.
                    string settingsPath   = "ProjectSettings/QualitySettings.asset";
                    string matchPattern   = @"(m_PerPlatformDefaultQuality.*Windows Store Apps:) (\d+)";
                    string replacePattern = @"$1 " + currentQualityLevel;

                    string settings = File.ReadAllText(settingsPath);
                    settings = Regex.Replace(settings, matchPattern, replacePattern, RegexOptions.Singleline);

                    File.WriteAllText(settingsPath, settings);
                }
                catch (Exception e)
                {
                    Debug.LogException(e);
                }
            }

            UnityEditorInternal.VR.VREditor.SetVREnabledOnTargetGroup(BuildTargetGroup.WSA, Values[ProjectSetting.WsaEnableVR]);
            if (Values[ProjectSetting.WsaEnableVR])
            {
                EditorUserBuildSettings.wsaSubtarget = WSASubtarget.HoloLens;
                UnityEditorInternal.VR.VREditor.SetVREnabledDevicesOnTargetGroup(BuildTargetGroup.WSA, new[] { "HoloLens" });
                PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.HumanInterfaceDevice, Values[ProjectSetting.XboxControllerSupport]);
            }
            else
            {
                EditorUserBuildSettings.wsaSubtarget = WSASubtarget.AnyDevice;
                PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.HumanInterfaceDevice, false);
            }

            EditorPrefsUtility.SetEditorPref(Names[ProjectSetting.SharingServices], Values[ProjectSetting.SharingServices]);
            if (Values[ProjectSetting.SharingServices])
            {
                string sharingServiceDirectory = Directory.GetParent(Path.GetFullPath(Application.dataPath)).FullName + "\\External\\HoloToolkit\\Sharing\\Server";
                string sharingServicePath      = sharingServiceDirectory + "\\SharingService.exe";
                if (!File.Exists(sharingServicePath) &&
                    EditorUtility.DisplayDialog("Attention!",
                                                "You're missing the Sharing Service Executable in your project.\n\n" +
                                                "Would you like to download the missing files from GitHub?\n\n" +
                                                "Alternatively, you can download it yourself.",
                                                "Yes", "Cancel"))
                {
                    try
                    {
                        using (var webRequest = UnityWebRequest.Get(SharingServiceURL))
                        {
                            webRequest.Send();

                            while (!webRequest.isDone)
                            {
                                if (webRequest.downloadProgress != -1)
                                {
                                    EditorUtility.DisplayProgressBar(
                                        "Downloading the SharingService executable from GitHub",
                                        "Progress...", webRequest.downloadProgress);
                                }
                            }
                            EditorUtility.ClearProgressBar();

#if UNITY_2017_1_OR_NEWER
                            if (webRequest.isNetworkError || webRequest.isHttpError)
#else
                            if (webRequest.isError)
#endif
                            {
                                throw new UnityException("Network Error: " + webRequest.error);
                            }

                            byte[] sharingServiceData = webRequest.downloadHandler.data;
                            Directory.CreateDirectory(sharingServiceDirectory);
                            File.WriteAllBytes(sharingServicePath, sharingServiceData);
                        }
                    }
                    catch (Exception)
                    {
                        Close();
                        throw;
                    }
                }
                else
                {
                    Debug.LogFormat("Alternatively, you can download from this link: {0}", SharingServiceURL);
                }

                PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.InternetClientServer, true);
                PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.PrivateNetworkClientServer, true);
            }
            else
            {
                PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.InternetClient, false);
                PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.InternetClientServer, false);
                PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.PrivateNetworkClientServer, false);
            }

            var  inputManagerPath = Directory.GetParent(Path.GetFullPath(Application.dataPath)).FullName + "\\ProjectSettings\\InputManager.asset";
            bool userPermission   = Values[ProjectSetting.XboxControllerSupport];

            if (userPermission)
            {
                userPermission = EditorUtility.DisplayDialog("Attention!",
                                                             "Hi there, we noticed that you've enabled the Xbox Controller support.\n\n" +
                                                             "Do you give us permission to download the latest input mapping definitions from " +
                                                             "the Mixed Reality Toolkit's GitHub page and replace your project's InputManager.asset?\n\n",
                                                             "OK", "Cancel");


                if (userPermission)
                {
                    try
                    {
                        using (var webRequest = UnityWebRequest.Get(InputManagerAssetURL)
                               )
                        {
                            webRequest.Send();

                            while (!webRequest.isDone)
                            {
                                if (webRequest.downloadProgress != -1)
                                {
                                    EditorUtility.DisplayProgressBar("Downloading InputManager.asset from GitHub",
                                                                     "Progress...", webRequest.downloadProgress);
                                }
                            }
                            EditorUtility.ClearProgressBar();

#if UNITY_2017_1_OR_NEWER
                            if (webRequest.isNetworkError || webRequest.isHttpError)
#else
                            if (webRequest.isError)
#endif
                            {
                                throw new UnityException("Network Error: " + webRequest.error);
                            }

                            File.Copy(inputManagerPath, inputManagerPath + ".old", true);
                            File.WriteAllText(inputManagerPath, webRequest.downloadHandler.text);
                        }
                    }
                    catch (Exception)
                    {
                        Close();
                        throw;
                    }
                }
            }

            if (!userPermission)
            {
                Values[ProjectSetting.XboxControllerSupport] = false;
                if (File.Exists(inputManagerPath + ".old"))
                {
                    File.Copy(inputManagerPath + ".old", inputManagerPath, true);
                    File.Delete(inputManagerPath + ".old");
                    Debug.Log("Previous Input Mapping Restored.");
                }
                else
                {
                    Debug.LogWarning("No old Input Mapping found!");
                }
            }
            EditorPrefsUtility.SetEditorPref(Names[ProjectSetting.XboxControllerSupport], Values[ProjectSetting.XboxControllerSupport]);

            AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
            Close();
        }
        /// <summary>
        /// Internal coroutine helper for receiving HTTP data from the DSS server using GET
        /// and processing it as needed
        /// </summary>
        /// <returns>the message</returns>
        private IEnumerator CO_GetAndProcessFromServer()
        {
            if (HttpServerAddress.Length == 0)
            {
                throw new InvalidOperationException("Cannot receive SDP messages from remote peer; invalid empty HTTP server address.");
            }
            if (LocalPeerId.Length == 0)
            {
                throw new InvalidOperationException("Cannot receive SDP messages from remote peer; invalid empty local peer ID.");
            }

            var www = UnityWebRequest.Get($"{HttpServerAddress}data/{LocalPeerId}");

            yield return(www.SendWebRequest());

            if (!www.isNetworkError && !www.isHttpError)
            {
                var json = www.downloadHandler.text;

                var msg = JsonUtility.FromJson <Message>(json);

                // if the message is good
                if (msg != null)
                {
                    // depending on what type of message we get, we'll handle it differently
                    // this is the "glue" that allows two peers to establish a connection.
                    Debug.Log($"Received SDP message: type={msg.MessageType} data={msg.Data}");
                    switch (msg.MessageType)
                    {
                    case Message.WireMessageType.Offer:
                        _nativePeer.SetRemoteDescriptionAsync("offer", msg.Data).Wait();
                        // if we get an offer, we immediately send an answer
                        _nativePeer.CreateAnswer();
                        break;

                    case Message.WireMessageType.Answer:
                        _ = _nativePeer.SetRemoteDescriptionAsync("answer", msg.Data);
                        break;

                    case Message.WireMessageType.Ice:
                        // this "parts" protocol is defined above, in OnIceCandiateReadyToSend listener
                        var parts = msg.Data.Split(new string[] { msg.IceDataSeparator }, StringSplitOptions.RemoveEmptyEntries);
                        // Note the inverted arguments; candidate is last here, but first in OnIceCandiateReadyToSend
                        _nativePeer.AddIceCandidate(parts[2], int.Parse(parts[1]), parts[0]);
                        break;

                    //case SignalerMessage.WireMessageType.SetPeer:
                    //    // this allows a remote peer to set our text target peer id
                    //    // it is primarily useful when one device does not support keyboard input
                    //    //
                    //    // note: when running this sample on HoloLens (for example) we may use postman or a similar
                    //    // tool to use this message type to set the target peer. This is NOT a production-quality solution.
                    //    TargetIdField.text = msg.Data;
                    //    break;
                    default:
                        Debug.Log("Unknown message: " + msg.MessageType + ": " + msg.Data);
                        break;
                    }

                    timeSincePollMs = PollTimeMs + 1f; //fast forward next request
                }
                else if (AutoLogErrors)
                {
                    Debug.LogError($"Failed to deserialize JSON message : {json}");
                }
            }
            else if (AutoLogErrors && www.isNetworkError)
            {
                Debug.LogError($"Network error trying to send data to {HttpServerAddress}: {www.error}");
            }
            else
            {
                // This is very spammy because the node-dss protocol uses 404 as regular "no data yet" message, which is an HTTP error
                //Debug.LogError($"HTTP error: {www.error}");
            }

            lastGetComplete = true;
        }
Exemplo n.º 5
0
        /// <summary>
        /// Allow the a pokemon data with its id
        /// </summary>
        /// <param name="id">id of the pokemon in API</param>
        /// <param name="callback">pokemon data, result</param>
        /// <returns></returns>
        public IEnumerator GetPokemonBaseData(int id, Action <PokemonData> callback)
        {
            id += 1; //The index start in 1

            string pokemonURL = basePokeURL + "pokemon/" + id.ToString();
            // Example URL: https://pokeapi.co/api/v2/pokemon/151

            //REQUEST
            UnityWebRequest pokeInfoRequest = UnityWebRequest.Get(pokemonURL);

            yield return(pokeInfoRequest.SendWebRequest());

            if (pokeInfoRequest.isNetworkError || pokeInfoRequest.isHttpError)
            {
                Debug.LogError(pokeInfoRequest.error);
                yield break;
            }

            //JSON PARSE
            JSONNode pokeInfo = JSON.Parse(pokeInfoRequest.downloadHandler.text);

            string name   = pokeInfo["name"];
            string weight = pokeInfo["weight"];
            string height = pokeInfo["height"];


            JSONNode pokeTypes = pokeInfo["types"];
            string   types     = "";

            for (int i = 0, j = pokeTypes.Count - 1; i < pokeTypes.Count; i++, j--)
            {
                types += pokeTypes[i]["type"]["name"] + " ";
            }

            //SPRITE REQUEST

            string[] spritesURL = new string[4];
            spritesURL[0] = pokeInfo["sprites"]["front_default"];
            spritesURL[1] = pokeInfo["sprites"]["back_default"];
            spritesURL[2] = pokeInfo["sprites"]["front_shiny"];
            spritesURL[3] = pokeInfo["sprites"]["back_shiny"];



            UnityWebRequest pokeSpriteRequest;

            Sprite[] sprites = new Sprite[4];


            for (int i = 0; i < 4; i++)
            {
                pokeSpriteRequest = UnityWebRequestTexture.GetTexture(spritesURL[i]);

                yield return(pokeSpriteRequest.SendWebRequest());

                if (pokeSpriteRequest.isNetworkError || pokeSpriteRequest.isHttpError)
                {
                    Debug.LogWarning(pokeSpriteRequest.error);

                    if (i > 0)
                    {
                        sprites[i] = Sprite.Create(sprites[i - 1].texture,
                                                   new Rect(0, 0, sprites[i - 1].texture.width, sprites[i - 1].texture.height),
                                                   new Vector2(0.5f, 0.5f));
                    }
                    else
                    {
                        sprites[i] = Sprite.Create(Texture2D.normalTexture,
                                                   new Rect(0, 0, Texture2D.normalTexture.width, Texture2D.normalTexture.height),
                                                   new Vector2(0.5f, 0.5f));
                    }
                }
                else
                {
                    Texture2D texture = DownloadHandlerTexture.GetContent(pokeSpriteRequest);

                    sprites[i] = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height),
                                               new Vector2(0.5f, 0.5f));
                }
            }

            //RESULT BUILD

            PokemonData newPokemon = new PokemonData(id + "", name, types, weight, height, sprites);

            callback(newPokemon);
        }
Exemplo n.º 6
0
    IEnumerator tryDownloadSprites()
    {
        FileInfoText.text = "Attempting to get mirror list...";
        yield return(new WaitForSeconds(longwaittime));

        UnityWebRequest www = UnityWebRequest.Get(host);

        www.SendWebRequest();
        while (!www.isDone)
        {
            FileInfoText.text = "Downloading: " + (www.downloadProgress * 100f).ToString("0.00") + "%";
            yield return(null);
        }

        if (www.isNetworkError || www.isHttpError)
        {
            FileInfoText.text = "Net Error: " + www.error;
            completeDownload(false);
            yield break;
        }

        FileInfoText.text = "Downloading: 100%";
        yield return(new WaitForSeconds(shortwaittime));

        FileInfoText.text = "Resolving hosts...";

        string[] hostLines = www.downloadHandler.text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
        www.Dispose();
        int  currentHost             = 0;
        bool downloadAndUnzipSuccess = false;

        yield return(null); // give us a frame before creating new request

        while (!downloadAndUnzipSuccess)
        {
            yield return(new WaitForSeconds(longwaittime));

            if (currentHost >= hostLines.Length)
            {
                FileInfoText.text = "Error: Ran out of hosts";
                completeDownload(false);
                yield break;
            }

            string hostToTry = hostLines[currentHost];
            FileInfoText.text = "Attempting to download sprites from: " + Environment.NewLine + ExtractDomainNameFromURL(hostToTry);
            yield return(new WaitForSeconds(longwaittime));

            UnityWebRequest wwwHost = UnityWebRequest.Get(hostToTry);
            wwwHost.SendWebRequest();

            while (!wwwHost.isDone)
            {
                FileInfoText.text = "Downloading: " + (wwwHost.downloadProgress * 100f).ToString("0.00") + "%";
                yield return(null);
            }

            if (wwwHost.isNetworkError || wwwHost.isHttpError)
            {
                FileInfoText.text = "Net Error: " + wwwHost.error;
                wwwHost.Dispose();
                yield return(new WaitForSeconds(longwaittime));

                currentHost++;
                continue;
            }
            else
            {
                //unzip
                FileInfoText.text = "Download complete. Saving file (lockup is ok)...";
                yield return(new WaitForSeconds(shortwaittime));

                //save to root
                string rootItemPath = Application.persistentDataPath + Path.DirectorySeparatorChar + filename;
                try
                {
                    if (!Directory.Exists(fileroot))
                    {
                        Directory.CreateDirectory(fileroot);
                    }
                    else
                    {
                        FileInfoText.text = "WARNING: Sprites found. Deleting directory...";
                        Directory.Delete(fileroot, true);
                    }

                    File.WriteAllBytes(rootItemPath, wwwHost.downloadHandler.data);
                    wwwHost.Dispose();
                }
                catch (Exception e)
                {
                    FileInfoText.text = "File Error: " + e.Message;
                    completeDownload(false);
                    yield break;
                }

                FileInfoText.text = "Attempting to unzip sprites (lockup is ok)...";
                yield return(new WaitForSeconds(shortwaittime));

                try
                {
                    System.IO.Compression.ZipFile.ExtractToDirectory(rootItemPath, fileroot);
                    File.Delete(rootItemPath);
                }
                catch (Exception e)
                {
                    FileInfoText.text = "Zip Error: " + e.Message;
                    currentHost++;
                    continue;
                }

                downloadAndUnzipSuccess = true;
                FileInfoText.text       = "Sprites created successfully";
                completeDownload(true);
            }
        }
    }
Exemplo n.º 7
0
        private IEnumerator SetupNewsTiles()
        {
            using (UnityWebRequest webRequest =
                       UnityWebRequest.Get("http://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/?appid=1178460&count=3&maxlength=110&format=json")) {
                // Request and wait for the desired page.
                yield return(webRequest.SendWebRequest());

                if (webRequest.isNetworkError || webRequest.isHttpError)
                {
                    Debug.LogError(webRequest.error);
                    yield break;
                }

                //Debug.Log(webRequest.downloadHandler.text);


                SteamAppNewsHolder appNewsHolder = JsonUtility.FromJson <SteamAppNewsHolder>(webRequest.downloadHandler.text);

                bool isFirst = true;

                foreach (SteamNewsItem item in appNewsHolder.appnews.newsitems)
                {
                    StartupApp_WelcomeTile tile = Instantiate(newsItemPF, tileSpawnRectTrans).GetComponent <StartupApp_WelcomeTile>();

                    //string version = item.title.Replace("Desktop Portal v", "");
                    int index = 0;
                    index = item.title.IndexOf("Portal v", StringComparison.Ordinal) + 8;
                    if (index != 0)
                    {
                        string version = item.title.Substring(index);
                        tile.versionText.SetText(version);

                        if (isFirst && version != DPSettings.config.lastSeenVersion)
                        {
                            tile.newIcon.SetActive(true);
                            DPSettings.config.lastSeenVersion = version;
                        }
                    }


                    if (item.tags.Contains("patchnotes"))
                    {
                        tile.title.SetText("Patch");
                    }

                    else
                    {
                        tile.title.SetText("Update");
                    }

                    tile.contents.SetText(item.contents);


                    tile.GetComponent <CUIOpenLink>().linkToLaunch = item.url;

                    //Get the image
                    using (UnityWebRequest announcementPage = UnityWebRequest.Get(item.url)) {
                        yield return(announcementPage.SendWebRequest());

                        //Debug.Log(announcementPage.downloadHandler.text);

                        string link = "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/clans/36888522/";

                        int j = announcementPage.downloadHandler.text.IndexOf(link, StringComparison.Ordinal) + link.Length;

                        for (int i = 0; i < 100; i++)
                        {
                            Char yay = announcementPage.downloadHandler.text[j + i];
                            if (yay.Equals('"'))
                            {
                                break;
                            }
                            else
                            {
                                link += yay;
                            }
                        }

                        //Download image:
                        using (UnityWebRequest imageRequest = UnityWebRequestTexture.GetTexture(link)) {
                            yield return(imageRequest.SendWebRequest());

                            if (imageRequest.isNetworkError || imageRequest.isHttpError)
                            {
                                Debug.LogError(imageRequest.error);
                            }
                            else
                            {
                                Texture img = ((DownloadHandlerTexture)imageRequest.downloadHandler).texture;

                                tile.bgImage.texture   = img;
                                tile.mainImage.texture = img;
                            }
                        }
                    }


                    isFirst = false;
                }
            }
        }
    public async void RunGrpcTest()
    {
        var cancellationTokenSource = new CancellationTokenSource();

        var interceptor = new AsyncAuthInterceptor(async(context, metadata) =>
        {
            // dummy token, with a "username" claim
            metadata.Add("authorization", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3QifQ.hNQI_r8BATy1LyXPr6Zuo9X_V0kSED8ngcqQ6G-WV5w");
        });

        string             address     = "" + testAddress + ":" + testPort;
        ChannelCredentials credentials = null;

        if (useTls)
        {
            var certUri = Path.Combine(Application.streamingAssetsPath, "ca.crt");
            var req     = UnityWebRequest.Get(certUri);
            await req.SendWebRequest();

            var cacert = req.downloadHandler.text;

            if (sendAuthToken)
            {
                credentials = ChannelCredentials.Create(new SslCredentials(cacert),
                                                        CallCredentials.FromInterceptor(interceptor));
            }
            else
            {
                credentials = new SslCredentials(cacert);
            }
        }
        else
        {
            credentials = ChannelCredentials.Insecure;
        }

        var channel = new Channel(address, credentials);

        var client = new Test.Grpc.Test.TestClient(channel);

        try {
            var sentTs = GetEpochTimestampNS();
            var pong   = await client.SendPingAsync(new Test.Grpc.Ping {
                EpochSendTimestampNS = sentTs
            },
                                                    deadline : DateTime.UtcNow.AddSeconds(10),
                                                    cancellationToken : cancellationTokenSource.Token);

            var receivedTs = pong.EpochSendTimestampNS;
            var delta      = receivedTs - sentTs;
            Debug.Log("Ping sent to Frontend (timestamp = " + sentTs + "),  Pong Received (timestamp = " + receivedTs + "), Round Trip = " + delta);

            Debug.Log("Opening test stream...");
            using (var streamCall = client.OpenTestStream(new Test.Grpc.Empty {
            },
                                                          new CallOptions(deadline: DateTime.UtcNow.AddSeconds(30),
                                                                          cancellationToken: cancellationTokenSource.Token)))
            {
                if (readStreamBeforeDispose)
                {
                    if (await streamCall.ResponseStream.MoveNext())
                    {
                        Debug.Log("Received Empty{} item on test stream");
                    }
                    else
                    {
                        Debug.Log("Nothing read from test stream");
                    }
                }
                else
                {
                    Debug.Log("Immediately disposing test stream");
                }
            }
        }
        finally
        {
            Debug.Log("Shutting down channel...");
            await channel.ShutdownAsync();
        }

        Debug.Log("Done");
    }
Exemplo n.º 9
0
        private IEnumerator RequestVersions()
        {
            OnMessage("正在获取版本信息...");
            if (Application.internetReachability == NetworkReachability.NotReachable)
            {
                var mb = MessageBox.Show("提示", "请检查网络连接状态", "重试", "退出");
                yield return(mb);

                if (mb.isOk)
                {
                    StartUpdate();
                }
                else
                {
                    Quit();
                }

                yield break;
            }

            var request = UnityWebRequest.Get(GetDownloadURL(Versions.Filename));

            request.downloadHandler = new DownloadHandlerFile(_savePath + Versions.Filename);
            yield return(request.SendWebRequest());

            var error = request.error;

            request.Dispose();
            if (!string.IsNullOrEmpty(error))
            {
                var mb = MessageBox.Show("提示", string.Format("获取服务器版本失败:{0}", error), "重试", "退出");
                yield return(mb);

                if (mb.isOk)
                {
                    StartUpdate();
                }
                else
                {
                    Quit();
                }

                yield break;
            }

            try
            {
                var v1 = Versions.LoadVersion(_savePath + Versions.Filename);           //网络版本文件
                var v2 = Versions.LoadVersion(_savePath + Versions.Filename + ".tmp");  //本地临时文件

                if (v2 > v1)
                {
                    //如果本地版本高于网络版本,就别更新了
                    OnComplete();
                    yield break;
                }

                //网络版本高于或者等于本地版本,则检查更新
                _versions = Versions.LoadVersions(_savePath + Versions.Filename, true);
                if (_versions.Count > 0)
                {
                    PrepareDownloads();
                    _step = Step.Prepared;
                }
                else
                {
                    OnComplete();
                }
            }
            catch (Exception e)
            {
                Debug.LogException(e);
                MessageBox.Show("提示", "版本文件加载失败", "重试", "退出").onComplete +=
                    delegate(MessageBox.EventId id)
                {
                    if (id == MessageBox.EventId.Ok)
                    {
                        StartUpdate();
                    }
                    else
                    {
                        Quit();
                    }
                };
            }
        }
Exemplo n.º 10
0
        public override System.Collections.Generic.IEnumerator <byte> GetData(GameDataSettings settings, System.Action <GameDataResult> onResult)
        {
            if (Application.isPlaying == false || this.serviceManager.logEnabled == true)
            {
                Debug.LogFormat("[ GameData ] Loading: {0}", settings.url);
            }

            var eTag         = settings.eTag;
            var eTagPrefsKey = "GameDataSystem.GoogleService.ETag";

            if (PlayerPrefs.HasKey(eTagPrefsKey) == true)
            {
                eTag = PlayerPrefs.GetString(eTagPrefsKey);
            }

            var www = UnityWebRequest.Get(settings.url);

            www.SetRequestHeader("ETag", eTag);
            www.Send();
                        #if UNITY_EDITOR
            if (Application.isPlaying == false)
            {
                while (www.isDone == false)
                {
                    if (UnityEditor.EditorUtility.DisplayCancelableProgressBar("Wait a while", "...", www.downloadProgress) == true)
                    {
                        break;
                    }
                }

                UnityEditor.EditorUtility.ClearProgressBar();

                eTag = www.GetResponseHeader("ETag");
                if (eTag != null)
                {
                    settings.eTag = eTag;
                    PlayerPrefs.SetString(eTagPrefsKey, eTag);
                }
            }
            else
            {
                        #endif

            while (www.isDone == false)
            {
                yield return(0);
            }

            eTag = www.GetResponseHeader("ETag");
            if (eTag != null)
            {
                PlayerPrefs.SetString(eTagPrefsKey, eTag);
            }

                        #if UNITY_EDITOR
        }
                        #endif

            onResult.Invoke(new GameDataResult()
            {
                hasError = !string.IsNullOrEmpty(www.error), data = www.downloadHandler.text, errorText = www.error
            });

            www.Dispose();
            www = null;
        }
Exemplo n.º 11
0
    IEnumerator GetStudentInfo()
    {
        //GET students' matriculation number in a tutorial group
        UnityWebRequest studentInfoRequest = UnityWebRequest.Get(baseStudentInfoURL);

        yield return(studentInfoRequest.SendWebRequest());

        if (studentInfoRequest.isNetworkError || studentInfoRequest.isHttpError)
        {
            //Debug.LogError(studentInfoRequest.error);
            yield break;
        }

        JSONNode studentInfo = JSON.Parse(studentInfoRequest.downloadHandler.text);


        //GET students' name from users
        UnityWebRequest usersRequest = UnityWebRequest.Get(baseUsersURL);

        yield return(usersRequest.SendWebRequest());

        if (usersRequest.isNetworkError || usersRequest.isHttpError)
        {
            yield break;
        }

        JSONNode userInfo = JSON.Parse(usersRequest.downloadHandler.text);


        //loop to get a list of student matriculation number in tutorial group
        for (int i = 0; i < studentInfo["student"].Count; i++)
        {
            matricNumberTextArray.Add(studentInfo["student"][i]);
            //Debug.Log();
            for (int j = 0; j < userInfo.Count; j++)
            {
                if (studentInfo["student"][i] == userInfo[j]["matricNo"])
                {
                    studentNameArray.Add(userInfo[j]["username"]);
                }
            }
        }


        studentList = matricNumberTextArray;


        studentNameList = new List <JSONNode>();
        studentNameList = studentNameArray;

        if (studentList.Count > 0)
        {
            noRecordLabel.gameObject.SetActive(false);
            RectTransform rt = (RectTransform)mainScrollContentView.transform;
            for (int i = 0; i < studentList.Count; i++)
            {
                string     value           = studentList[i];
                string     studentName     = studentNameList[i];
                GameObject playerTextPanel = (GameObject)Instantiate(ContentDataPanel);
                playerTextPanel.transform.SetParent(mainScrollContentView.transform);
                playerTextPanel.transform.localScale    = new Vector3(1, 1, 1);
                playerTextPanel.transform.localPosition = new Vector3(0, 0, 0);
                playerTextPanel.transform.Find("Text_No").GetComponent <Text>().text     = i.ToString();
                playerTextPanel.transform.Find("Text_Matric").GetComponent <Text>().text = value;
                playerTextPanel.transform.Find("Text_Name").GetComponent <Text>().text   = studentName;

                playerTextPanel.transform.Find("Text_Name").transform.Find("Button_View").GetComponent <Button>().onClick.AddListener(() => {
                    matricNumber    = playerTextPanel.transform.Find("Text_Matric").GetComponent <Text>().text;
                    studentUsername = playerTextPanel.transform.Find("Text_Name").GetComponent <Text>().text;
                    viewStudent();
                });
            }
        }
        else
        {
            noRecordLabel.gameObject.SetActive(true);
        }
    }
Exemplo n.º 12
0
    IEnumerator GetText()
    {
        UnityWebRequest www = UnityWebRequest.Get("http://18.223.239.177/hello/allmodules");

        yield return(www.SendWebRequest());

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            quizData = www.downloadHandler.text;
            //string str = "{\"Q\":[" + quizData + "]}";
            QuizModel[] qarray = JsonHelper.getJsonArray <QuizModel>(quizData);

            MyQuiz = Parser.Parse(quizData);

            q = MyQuiz;
            foreach (QuizModel qm in qarray)
            {
                string str   = qm.name.ToLower();
                string title = "";
                for (int i = 0; i < 3; i++)
                {
                    title += str[i];
                }
                if (title != "pri" && title != "sec" && title != "jun" && title != "pol" && title != "bac" && title != "mas" && title != "phd")
                {
                    title = qm.name;
                }
                switch (title)
                {
                case "pri":
                    db.QuizesPri.Add(qm);
                    break;

                case "sec":
                    db.QuizesSec.Add(qm);
                    break;

                case "jun":
                    db.QuizesJun.Add(qm);
                    break;

                case "pol":
                    db.QuizesPol.Add(qm);
                    break;

                case "bac":
                    db.QuizesBac.Add(qm);
                    break;

                case "mas":
                    db.QuizesMas.Add(qm);
                    break;

                case "phd":
                    db.QuizesPhd.Add(qm);
                    break;

                case "Chief Financial Officer":
                    Debug.Log("==============-------------------================--------------------- ADDED");
                    db.Quizes_Chief_Financial_Officer.Add(qm);
                    break;

                case "Management Accounting - Accounting Executive":
                    db.Quizes_Management_Accounting_Accounting_Executive.Add(qm);
                    break;

                case "Management Accounting - Financial Planning and Analysis Manager":
                    db.Quizes_Management_Accounting_Financial_Planning_and_Analysis_Manager.Add(qm);
                    break;

                case "Management Accounting - Business Controller":
                    db.Quizes_Management_Accounting_Business_Controller.Add(qm);
                    break;

                case "Financial Accounting - Accounts Executive":
                    db.Quizes_Financial_Accounting_Accounts_Executive.Add(qm);
                    break;

                case "Financial Accounting - Finance Manager":
                    db.Quizes_Financial_Accounting_Finance_Manager.Add(qm);
                    break;

                case "Financial Accounting - Financial Controller":
                    db.Quizes_Financial_Accounting_Financial_Controller.Add(qm);
                    break;

                case "Senior Principal Physiotherapy Researcher":
                    db.Quizes_Senior_Principal_Physiotherapy_Researcher.Add(qm);
                    break;

                case "Senior Principal Physiotherapist (Clinical)":
                    db.Quizes_Senior_Principal_Physiotherapist_Clinical.Add(qm);
                    break;

                case "Senior Principal Physiotherapy Educator":
                    db.Quizes_Senior_Principal_Physiotherapy_Educator.Add(qm);
                    break;

                case "Principal Physiotherapy Educator":
                    db.Quizes_Principal_Physiotherapy_Educator.Add(qm);
                    break;

                case "Principal Physiotherapist (Clinical)":
                    db.Quizes_Principal_Physiotherapist_Clinical.Add(qm);
                    break;

                case "Principal Physiotherapy Researcher":
                    db.Quizes_Principal_Physiotherapy_Researcher.Add(qm);
                    break;

                case "Senior Physiotherapist":
                    db.Quizes_Senior_Physiotherapist.Add(qm);
                    break;

                case "Physiotherapist":
                    db.Quizes_Physiotherapist.Add(qm);
                    break;

                case "Chief Human Resource Officer":
                    db.Quizes_Chief_Human_Resource_Officer.Add(qm);
                    break;

                case "Head, Performance & Rewards":
                    db.Quizes_Head_Performance_Rewards.Add(qm);
                    break;

                case "Manager, Performance & Rewards":
                    db.Quizes_Manager_Performance_Rewards.Add(qm);
                    break;

                case "Executive, Performance & Rewards":
                    db.Quizes_Executive_Performance_Rewards.Add(qm);
                    break;

                case "Head, Employee Experience & Relations":
                    db.Quizes_Head_Employee_Experience_Relations.Add(qm);
                    break;

                case "Manager, Employee Experience & Relations":
                    db.Quizes_Manager_Employee_Experience_Relations.Add(qm);
                    break;

                case "Executive, Employee Experience & Relations":
                    db.Quizes_Executive_Employee_Experience_Relations.Add(qm);
                    break;

                case "Head, Talent & Attraction":
                    db.Quizes_Head_Talent_Attraction.Add(qm);
                    break;

                case "Manager, Talent & Attraction":
                    db.Quizes_Manager_Talent_Attraction.Add(qm);
                    break;

                case "Executive, Talent & Attraction":
                    db.Quizes_Executive_Talent_Attraction.Add(qm);
                    break;

                case "Head of Product":
                    db.Quizes_Head_of_Product.Add(qm);
                    break;

                case "Lead UX Designer":
                    db.Quizes_Lead_UX_Designer.Add(qm);
                    break;

                case "Senior UX Designer":
                    db.Quizes_Senior_UX_Designer.Add(qm);
                    break;

                case "UX Designer":
                    db.Quizes_UX_Designer.Add(qm);
                    break;

                case "Chief Technology Officer":
                    db.Quizes_Chief_Technology_Officer.Add(qm);
                    break;

                case "Applications Architect":
                    db.Quizes_Applications_Architect.Add(qm);
                    break;

                case "Applications Development Manager":
                    db.Quizes_Applications_Development_Manager.Add(qm);
                    break;

                case "Applications Developer":
                    db.Quizes_Applications_Developer.Add(qm);
                    break;

                case "Executive Producer - Broadcast":
                    db.Quizes_Executive_Producer_Broadcast.Add(qm);
                    break;

                case "Producer - Broadcast":
                    db.Quizes_Producer_Broadcast.Add(qm);
                    break;

                case "Assistant Producer Broadcast":
                    db.Quizes_Assistant_Producer_Broadcast.Add(qm);
                    break;

                case "Production Assistant":
                    db.Quizes_Production_Assistant.Add(qm);
                    break;

                case "Chief Editor":
                    db.Quizes_Chief_Editor.Add(qm);
                    break;

                case "Executive Editor":
                    db.Quizes_Executive_Editor.Add(qm);
                    break;

                case "Senior Reporter / Senior Correspondent":
                    db.Quizes_Senior_Reporter_Senior_Correspondent.Add(qm);
                    break;

                case "Reporter / Correspondent":
                    db.Quizes_Reporter_Correspondent.Add(qm);
                    break;

                case "Chief Executive Officer / Managing Director":
                    db.Quizes_Chief_Executive_Officer_Managing_Director.Add(qm);
                    break;

                case "Brand Director":
                    db.Quizes_Brand_Director.Add(qm);
                    break;

                case "Brand Manager":
                    db.Quizes_Brand_Manager.Add(qm);
                    break;

                case "Brand Associate":
                    db.Quizes_Brand_Associate.Add(qm);
                    break;

                case "Merchandising Director":
                    db.Quizes_Merchandising_Director.Add(qm);
                    break;

                case "Merchandising Manager":
                    db.Quizes_Merchandising_Manager.Add(qm);
                    break;

                case "Visual Merchandiser":
                    db.Quizes_Visual_Merchandiser.Add(qm);
                    break;

                case "Accountancy":
                    db.Quizes_AC.Add(qm);
                    break;

                case "Healthcare":
                    db.Quizes_HC.Add(qm);
                    break;

                case "Human Resources":
                    db.Quizes_HR.Add(qm);
                    break;

                case "Information Technology":
                    db.Quizes_IT.Add(qm);
                    break;

                case "Retail":
                    db.Quizes_RE.Add(qm);
                    break;

                case "Media":
                    db.Quizes_ME.Add(qm);
                    break;
                }
            }
            //          db.Quizes = q;
//            Debug.Log("quizzes loaded: " + MyQuiz[0].questions.Length);
        }
    }
    public IEnumerator SendRequest <T>(YNoteRequestData data, Action <T> cb)
    {
        Log.send(data.ToString());
        Log.SaveToFile("send", data.ToString());

        UnityWebRequest request;

        switch (data.httpVerb)
        {
        default:
        case HTTPVerb.GET:
            request = UnityWebRequest.Get(data.url);
            break;

        case HTTPVerb.POST:
        {
            switch (data.contentType)
            {
            default:
            case HTTPContentType.DEFAULT:
            case HTTPContentType.APPLICATION:
                request = UnityWebRequest.Post(data.url, data.content);
                break;

            case HTTPContentType.MULTIPART:
            {
                List <IMultipartFormSection> multipartFormSections = new List <IMultipartFormSection>();
                foreach (var kvp in data.content)
                {
                    multipartFormSections.Add(new MultipartFormDataSection(kvp.Key, kvp.Value, YNoteOAuthUtil.GetHttpContentType(data.contentType)));
                }
                request = UnityWebRequest.Post(data.url, multipartFormSections);
                request.uploadHandler.contentType = YNoteOAuthUtil.GetHttpContentType(data.contentType);
            }
            break;
            }
        }
        break;
        }
        yield return(request.Send());

        YNoteResponseData response = new YNoteResponseData();

        response.errorMsg         = request.error;
        response.httpResponseCode = request.responseCode;

        if (request.isNetworkError)
        {
            response.type = ResponseType.Error;
            Log.e("NetworkError", request.error);
        }
        else
        {
            response.type = ResponseType.Success;

            Log.d("HttpCode", request.responseCode);
            string text    = request.downloadHandler.text;
            byte[] results = request.downloadHandler.data;
            response.text = text;

            switch (request.responseCode)
            {
            case 200:
            {
                if (StringUtil.IsHtmlStrSimple(text))
                {
                    Log.w("recv", "is html!");
                    break;
                }
                if (StringUtil.IsOAuthStrSimple(text))
                {
                    text = StringUtil.OAuthStr2JsonStr(text);
                }
                if (StringUtil.IsJsonStrSimple(text))
                {
                    T result = JsonConvert.DeserializeObject <T>(text);
                    if (cb != null)
                    {
                        cb(result);
                    }
                }
            }
            break;
            }
        }

        Log.recv(response.ToString());
        Log.SaveToFile("recv", response.ToString());

        if (defaultCB != null)
        {
            defaultCB(response);
        }
    }
Exemplo n.º 14
0
    IEnumerator Start()
    {
        webViewObject = (new GameObject("WebViewObject")).AddComponent <WebViewObject>();
        webViewObject.Init(
            cb: (msg) =>
        {
            Debug.Log(string.Format("CallFromJS[{0}]", msg));
            status.text = msg;
            status.GetComponent <Animation>().Play();
        },
            err: (msg) =>
        {
            Debug.Log(string.Format("CallOnError[{0}]", msg));
            status.text = msg;
            status.GetComponent <Animation>().Play();
        },
            started: (msg) =>
        {
            Debug.Log(string.Format("CallOnStarted[{0}]", msg));
        },
            hooked: (msg) =>
        {
            Debug.Log(string.Format("CallOnHooked[{0}]", msg));
        },
            ld: (msg) =>
        {
            Debug.Log(string.Format("CallOnLoaded[{0}]", msg));
#if UNITY_EDITOR_OSX || !UNITY_ANDROID
            // NOTE: depending on the situation, you might prefer
            // the 'iframe' approach.
            // cf. https://github.com/gree/unity-webview/issues/189
#if true
            webViewObject.EvaluateJS(@"
                  if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) {
                    window.Unity = {
                      call: function(msg) {
                        window.webkit.messageHandlers.unityControl.postMessage(msg);
                      }
                    }
                  } else {
                    window.Unity = {
                      call: function(msg) {
                        window.location = 'unity:' + msg;
                      }
                    }
                  }
                ");
#else
            webViewObject.EvaluateJS(@"
                  if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) {
                    window.Unity = {
                      call: function(msg) {
                        window.webkit.messageHandlers.unityControl.postMessage(msg);
                      }
                    }
                  } else {
                    window.Unity = {
                      call: function(msg) {
                        var iframe = document.createElement('IFRAME');
                        iframe.setAttribute('src', 'unity:' + msg);
                        document.documentElement.appendChild(iframe);
                        iframe.parentNode.removeChild(iframe);
                        iframe = null;
                      }
                    }
                  }
                ");
#endif
#endif
            webViewObject.EvaluateJS(@"Unity.call('ua=' + navigator.userAgent)");
        },
            //ua: "custom user agent string",
            enableWKWebView: true);
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
        webViewObject.bitmapRefreshCycle = 1;
#endif
        //webViewObject.SetAlertDialogEnabled(false);
        //webViewObject.SetURLPattern("", "^https://.*youtube.com", "^https://.*google.com");
        webViewObject.SetMargins(5, 100, 5, Screen.height / 4);
        webViewObject.SetVisibility(true);

#if !UNITY_WEBPLAYER && !UNITY_WEBGL
        if (Url.StartsWith("http"))
        {
            webViewObject.LoadURL(Url.Replace(" ", "%20"));
        }
        else
        {
            var exts = new string[] {
                ".jpg",
                ".js",
                ".html"  // should be last
            };
            foreach (var ext in exts)
            {
                var    url    = Url.Replace(".html", ext);
                var    src    = System.IO.Path.Combine(Application.streamingAssetsPath, url);
                var    dst    = System.IO.Path.Combine(Application.persistentDataPath, url);
                byte[] result = null;
                if (src.Contains("://"))    // for Android
                {
#if UNITY_2018_4_OR_NEWER
                    // NOTE: a more complete code that utilizes UnityWebRequest can be found in https://github.com/gree/unity-webview/commit/2a07e82f760a8495aa3a77a23453f384869caba7#diff-4379160fa4c2a287f414c07eb10ee36d
                    var unityWebRequest = UnityWebRequest.Get(src);
                    yield return(unityWebRequest.SendWebRequest());

                    result = unityWebRequest.downloadHandler.data;
#else
                    var www = new WWW(src);
                    yield return(www);

                    result = www.bytes;
#endif
                }
                else
                {
                    result = System.IO.File.ReadAllBytes(src);
                }
                System.IO.File.WriteAllBytes(dst, result);
                if (ext == ".html")
                {
                    webViewObject.LoadURL("file://" + dst.Replace(" ", "%20"));
                    break;
                }
            }
        }
#else
        if (Url.StartsWith("http"))
        {
            webViewObject.LoadURL(Url.Replace(" ", "%20"));
        }
        else
        {
            webViewObject.LoadURL("StreamingAssets/" + Url.Replace(" ", "%20"));
        }
        webViewObject.EvaluateJS(
            "parent.$(function() {" +
            "   window.Unity = {" +
            "       call:function(msg) {" +
            "           parent.unityWebView.sendMessage('WebViewObject', msg)" +
            "       }" +
            "   };" +
            "});");
#endif
        yield break;
    }
    IEnumerator GetWifi()
    {
        connecting.gameObject.SetActive(false);
        fetchingData.gameObject.SetActive(true);
        UnityWebRequest www = UnityWebRequest.Get("http://192.168.240.1/wifi/scan");

        //yield return new WaitForSeconds(3);
        yield return(www.SendWebRequest());

        www.Abort();
        www = UnityWebRequest.Get("http://192.168.240.1/wifi/scan");
        yield return(www.SendWebRequest());


        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            ResultClass result = JsonConvert.DeserializeObject <ResultClass>(www.downloadHandler.text);
            // Show results as text
            Debug.Log(www.downloadHandler.text);
            Array.Sort(result.result.Aps);

            for (int x = 0; x < 4 && x < result.result.Aps.Length; x++)
            {
                float size = 0;
                if (Single.TryParse(result.result.Aps[x].rssi, out size))
                {
                    if (size > -20)
                    {
                        continue;
                    }
                    size          = (size + 100f) * 1.2f;
                    size         /= 100f;
                    texts[x].text = result.result.Aps[x].essid;
                    aps[x].SetActive(true);
                    texts[x].gameObject.SetActive(true);

                    switch (result.result.Aps[x].enc)
                    {
                    case "WEP":
                        aps[x].transform.GetChild(0).GetComponent <Renderer>().material = WepMaterial;
                        break;

                    case "WPA":
                        aps[x].transform.GetChild(0).GetComponent <Renderer>().material = WpaMaterial;
                        break;

                    case "WPA2":
                        aps[x].transform.GetChild(0).GetComponent <Renderer>().material = Wpa2Material;
                        break;

                    case "None":
                        aps[x].transform.GetChild(0).GetComponent <Renderer>().material = NoneMaterial;
                        break;

                    case "Auto":
                        aps[x].transform.GetChild(0).GetComponent <Renderer>().material = AutoMaterial;
                        break;
                    }
                }
                aps[x].transform.localScale = new Vector3(size, 1f, 1f);
            }
        }
        fetchingData.gameObject.SetActive(false);
    }
Exemplo n.º 16
0
    private IEnumerator Connection()
    {
        while (true)
        {
            string currentURL = URL + thisMachine_number + "&last_door=" + currentID;

            Debug.Log(currentURL);

            UnityWebRequest request = UnityWebRequest.Get(currentURL);

            // リクエスト送信
            request.SendWebRequest();

            yield return(new WaitForSeconds(requestInterval));

            if (request.isNetworkError)
            {
                Debug.Log("エラー:" + request.error);
            }
            else
            {
                if (request.responseCode == 200)
                {
                    network_status = "Success.";

                    Debug.Log(request.downloadHandler.text);

                    responce = request.downloadHandler.text;


                    //デバッグモード
                    if (Debugmode)
                    {
                        string Data = "";

                        int length = Random.Range(0, 8);

                        for (int i = 0; i < length; i++)
                        {
                            string tex_ID = Random.Range(0, 5).ToString();

                            string BaseColor_ID = Random.Range(0, 5).ToString();

                            string TexColor_ID = Random.Range(0, 5).ToString();


                            string randomData = "0.0." +
                                                tex_ID + "." +
                                                BaseColor_ID + "." +
                                                TexColor_ID + "/";

                            Data += randomData;
                        }

                        if (Probability(50))
                        {
                            Data = "";
                        }

                        responce = Data;
                    }

                    DataBlocks.Clear();
                    processData();

                    if (DataBlocks.Count > 0)
                    {
                        //DataBlockの末尾のidを代入
                        string[] lastData = SplitData(DataBlocks[DataBlocks.Count - 1], '.');
                        currentID = int.Parse(lastData[0]);
                        currentID++;
                        Debug.Log(currentID);
                    }


                    LogText.text += "\n" + network_status + "current ID : " + currentID;
                }

                else
                {
                    network_status = "Failed... : " + request.responseCode;

                    LogText.text += "\n" + network_status;

                    responce = "E.x.a.m.p./l.e.E.x.a./m.p.l.e.E./x.a.m.p.l./";
                }
            }
        }
    }
Exemplo n.º 17
0
    // Initialization:
    void Start()
    {
        me = GCHandle.Alloc(this);

        if (RecognitionInterval == 0)
        {
            RecognitionInterval = 0.1f;
        }
        if (GesturePeriod == 0)
        {
            GesturePeriod = 1.0f;
        }

        // Load the set of gestures.
        if (LoadGesturesFile == null)
        {
            LoadGesturesFile = "Sample_Continuous_Gestures.dat";
        }

        // Find the location for the gesture database (.dat) file
#if UNITY_EDITOR
        // When running the scene inside the Unity editor,
        // we can just load the file from the Assets/ folder:
        string GesturesFilePath = "Assets/GestureRecognition";
#elif UNITY_ANDROID
        // On android, the file is in the .apk,
        // so we need to first "download" it to the apps' cache folder.
        AndroidJavaClass  unityPlayer      = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject activity         = unityPlayer.GetStatic <AndroidJavaObject>("currentActivity");
        string            GesturesFilePath = activity.Call <AndroidJavaObject>("getCacheDir").Call <string>("getCanonicalPath");
        UnityWebRequest   request          = UnityWebRequest.Get(Application.streamingAssetsPath + "/" + LoadGesturesFile);
        request.SendWebRequest();
        while (!request.isDone)
        {
            // wait for file extraction to finish
        }
        if (request.isNetworkError)
        {
            HUDText.text = "Failed to extract sample gesture database file from apk.";
            return;
        }
        File.WriteAllBytes(GesturesFilePath + "/" + LoadGesturesFile, request.downloadHandler.data);
#else
        // This will be the case when exporting a stand-alone PC app.
        // In this case, we can load the gesture database file from the streamingAssets folder.
        string GesturesFilePath = Application.streamingAssetsPath;
#endif
        int ret = gr.loadFromFile(GesturesFilePath + "/" + LoadGesturesFile);
        if (ret != 0)
        {
            HUDText.text = $"Failed to load sample gesture database file ({ret})\n";
            return;
        }
        gr.contdIdentificationSmoothing = 5;

        // Hide unused models in the scene
        GameObject controller_oculus_left     = GameObject.Find("controller_oculus_left");
        GameObject controller_oculus_right    = GameObject.Find("controller_oculus_right");
        GameObject controller_vive_left       = GameObject.Find("controller_vive_left");
        GameObject controller_vive_right      = GameObject.Find("controller_vive_right");
        GameObject controller_microsoft_left  = GameObject.Find("controller_microsoft_left");
        GameObject controller_microsoft_right = GameObject.Find("controller_microsoft_right");
        GameObject controller_dummy_left      = GameObject.Find("controller_dummy_left");
        GameObject controller_dummy_right     = GameObject.Find("controller_dummy_right");

        controller_oculus_left.SetActive(false);
        controller_oculus_right.SetActive(false);
        controller_vive_left.SetActive(false);
        controller_vive_right.SetActive(false);
        controller_microsoft_left.SetActive(false);
        controller_microsoft_right.SetActive(false);
        controller_dummy_left.SetActive(false);
        controller_dummy_right.SetActive(false);

        var input_devices = new List <UnityEngine.XR.InputDevice>();
        UnityEngine.XR.InputDevices.GetDevices(input_devices);
        String input_device = "";
        foreach (var device in input_devices)
        {
            if (device.characteristics.HasFlag(InputDeviceCharacteristics.HeadMounted))
            {
                input_device = device.name;
                break;
            }
        }

        if (input_device.Length >= 6 && input_device.Substring(0, 6) == "Oculus")
        {
            controller_oculus_left.SetActive(true);
            controller_oculus_right.SetActive(true);
        }
        else if (input_device.Length >= 4 && input_device.Substring(0, 4) == "Vive")
        {
            controller_vive_left.SetActive(true);
            controller_vive_right.SetActive(true);
        }
        else if (input_device.Length >= 4 && input_device.Substring(0, 4) == "DELL")
        {
            controller_microsoft_left.SetActive(true);
            controller_microsoft_right.SetActive(true);
        }
        else //
        {
            controller_dummy_left.SetActive(true);
            controller_dummy_right.SetActive(true);
        }

        GameObject star = GameObject.Find("star");
        star.transform.localScale = new Vector3(0.0f, 0.0f, 0.0f);
        GameObject controller_dummy = GameObject.Find("controller_dummy");
        controller_dummy.transform.localScale = new Vector3(0.0f, 0.0f, 0.0f);


        // Set the welcome message.
        HUDText      = GameObject.Find("HUDText").GetComponent <Text>();
        HUDText.text = "Welcome to MARUI Gesture Plug-in!\n"
                       + "Hold the trigger to draw gestures.\nAvailable gestures:";
        for (int i = 0; i < gr.numberOfGestures(); i++)
        {
            HUDText.text += "\n" + (i + 1) + " : " + gr.getGestureName(i);
        }
        HUDText.text += "\nor: press 'A'/'X'/Menu button\nto create new gesture.";
    }
Exemplo n.º 18
0
    IEnumerator DownloadModelOrGetFromCache(int pos, Models modelsList)
    {
        Debug.Log(pos);
        // Wait for the Caching system to be ready
        while (!Caching.ready)
        {
            yield return(null);
        }

        float maxProgress = 1;
        float progress    = 0;

        // get current bundle hash from server, random value added to avoid caching
        UnityWebRequest www =
            UnityWebRequest.Get(modelsList.body[pos].model_url + ".manifest?r=" + (Random.value * 9999999));

        Debug.Log("Loading manifest:" + modelsList.body[pos].model_url + ".manifest");

        // wait for load to finish
        yield return(www.SendWebRequest());

        // if received error, exit
        if (www.isNetworkError == true)
        {
            Debug.LogError("www error: " + www.error);
            www.Dispose();
            www = null;
            yield break;
        }

        // create empty hash string
        Hash128 hashString = (default(Hash128)); // new Hash128(0, 0, 0, 0);

        // check if received data contains 'ManifestFileVersion'
        if (www.downloadHandler.text.Contains("ManifestFileVersion"))
        {
            // extract hash string from the received data, TODO should add some error checking here
            var hashRow = www.downloadHandler.text.ToString().Split("\n".ToCharArray())[5];
            hashString = Hash128.Parse(hashRow.Split(':')[1].Trim());

            if (hashString.isValid == true)
            {
                // we can check if there is cached version or not
                if (Caching.IsVersionCached(modelsList.body[pos].model_url, hashString) == true)
                {
                    Debug.Log("Bundle with this hash is already cached!");
                }
                else
                {
                    Debug.Log("No cached version founded for this hash..");
                }
            }
            else
            {
                // invalid loaded hash, just try loading latest bundle
                Debug.LogError("Invalid hash:" + hashString);
                yield break;
            }
        }
        else
        {
            Debug.LogError("Manifest doesn't contain string 'ManifestFileVersion': " + modelsList.body[pos].model_url +
                           ".manifest");
            yield break;
        }


        // now download the actual bundle, with hashString parameter it uses cached version if available
        www = UnityWebRequestAssetBundle.GetAssetBundle(
            modelsList.body[pos].model_url + "?r=" + (Random.value * 9999999), hashString, 0);

        // wait for load to finish
        www.SendWebRequest();

        if (www.error != null)
        {
            Debug.LogError("www error: " + www.error);
            www.Dispose();
            www = null;
            yield break;
        }
        else
        {
            //To remember the last progress
            float lastProgress = progress;
            //informationBox.text = "Downloading resources...";
            while (!www.isDone)
            {
                //Calculate the current progress
                progress = lastProgress + www.downloadProgress;
                //Get a percentage
                float progressPercentage = (progress / maxProgress) * 100;
                Debug.Log("Downloaded: " + progressPercentage + "%");
                yield return(new WaitForSeconds(0.1f));
                //slider.value = Mathf.Clamp01(progress / maxProgress);
            }

            bundle = DownloadHandlerAssetBundle.GetContent(www);
            Debug.Log("Download Completed.");

            //Add the model and parent combination to list for later instantiation
            ModelsParents modelsParents = new ModelsParents();
            //Downloaded Asset Bundle
            modelsParents.Bundle = bundle;
            //Asset Bundle Name
            modelsParents.Name = modelsList.body[pos].prefab_name;
            //GameObject for the model to be placed in
            modelsParents.Parent = parent;
            //Model Show Text
            modelsParents.ModelShowText = modelsList.body[pos].model_show_text;

            StartCoroutine(CreateFinalObject(modelsParents));
        }
    }
Exemplo n.º 19
0
 protected UnityWebRequest HttpGetCreator(string endpoint, Dictionary <string, string> uri_parameters = null)
 {
     return(UnityWebRequest.Get(UriCreator(endpoint, uri_parameters)));
 }
    IEnumerator HandleObjectRecognitionBaidu()
    {
        using (UnityWebRequest webRequest = UnityWebRequest.Get("http://10.128.58.107:5000/bceimagetagoptions"))
        {
            // Request and wait for the desired page.
            yield return(webRequest.SendWebRequest());

            if (!webRequest.isNetworkError)
            {
                m_ImageInfo.text = webRequest.downloadHandler.text;
                byte[] bytes        = m_Texture.EncodeToPNG();
                string base64String = Convert.ToBase64String(bytes);
                //string encodedBase64String = Uri.EscapeUriString(base64String);
                List <IMultipartFormSection> formData = new List <IMultipartFormSection>();
                formData.Add(new MultipartFormDataSection("image", base64String));
                UnityWebRequest bceRequest = UnityWebRequest.Post(webRequest.downloadHandler.text, formData);
                yield return(bceRequest.SendWebRequest());

                if (!bceRequest.isNetworkError && !bceRequest.isHttpError)
                {
                    m_ImageInfo.text = bceRequest.downloadHandler.text;
                    ObjRecognitionResult resultObj = JsonConvert.DeserializeObject <ObjRecognitionResult>(m_ImageInfo.text);
                    if (resultObj.result.Count > 0)
                    {
                        ObjRecognitionResult.RecognitionResultItem firstItem = resultObj.result[0];
                        string tag = firstItem.root + firstItem.keyword;
                        if (m_ChineseToEnglishMap.ContainsKey(tag))
                        {
                            Speaker.Speak("result is: " + m_ChineseToEnglishMap[tag] + ", score is: " + firstItem.score.ToString());
                        }
                        else
                        {
                            yield return(StartCoroutine(translateResultWithGoogleApi(firstItem.keyword)));

                            Console.WriteLine("m_ChineseToEnglishMap.Add(\"" + tag + "\", \"" + m_TranslatedResult + "\");");
                            m_ChineseToEnglishMap.Add(tag, m_TranslatedResult);
                            Speaker.Speak("result is: " + m_TranslatedResult + ", score is: " + firstItem.score.ToString());
                        }
                        foreach (var item in resultObj.result)
                        {
                            tag = item.root + item.keyword;
                            if (!m_ChineseToEnglishMap.ContainsKey(tag))
                            {
                                yield return(StartCoroutine(translateResultWithGoogleApi(item.keyword)));

                                Console.WriteLine("m_ChineseToEnglishMap.Add(\"" + tag + "\", \"" + m_TranslatedResult + "\");");
                                m_ChineseToEnglishMap.Add(tag, m_TranslatedResult);
                            }
                        }
                    }
                }
                else
                {
                    m_ImageInfo.text = "get from bce error";
                }
            }
            else
            {
                m_ImageInfo.text = "get from token server error";
            }
        }
    }
Exemplo n.º 21
0
        public static async Task <T> GetVideoMetaDataAsync <T>(string youtubeUrl, YoutubeDlOptions options,
                                                               IEnumerable <string> schema, CancellationToken cancellationToken = default)
        {
            var optionFlags = new List <string>();

            if (!string.IsNullOrWhiteSpace(options.Format))
            {
                optionFlags.Add($"-f \"{options.Format}\"");
            }
            if (options.UserAgent != null)
            {
                optionFlags.Add($"--user-agent \"{options.UserAgent}\"");
            }
            if (options.Custom != null)
            {
                optionFlags.Add(options.Custom);
            }

            var requestUrl = $"{ServerUrl}/v1/video?url={youtubeUrl}";

            if (optionFlags.Count > 0)
            {
                requestUrl += $"&options={UnityWebRequest.EscapeURL(string.Join(" ", optionFlags))}";
            }

            if (schema != null)
            {
                foreach (var schemaKey in schema)
                {
                    requestUrl += $"&schema={schemaKey}";
                }
            }

            var request = UnityWebRequest.Get(requestUrl);
            var tcs     = new TaskCompletionSource <T>();

            request.SendWebRequest().completed += operation =>
            {
#if UNITY_2020_2_OR_NEWER
                if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.DataProcessingError)
#else
                if (request.isNetworkError)
#endif
                {
                    tcs.TrySetException(new Exception(request.error));
                    return;
                }

                var text = request.downloadHandler.text;

#if UNITY_2020_2_OR_NEWER
                if (request.result == UnityWebRequest.Result.ProtocolError)
#else
                if (request.isHttpError)
#endif
                {
                    tcs.TrySetException(new Exception(request.error + "\nResponseError:" + text));
                    return;
                }

                var video = JsonConvert.DeserializeObject <T>(text);
                tcs.TrySetResult(video);
            };

            cancellationToken.Register(obj =>
            {
                ((UnityWebRequest)obj).Abort();
                tcs.TrySetCanceled(cancellationToken);
            }, request);

            return(await tcs.Task);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="url"></param>
        private void GetUrl(string url)
        {
            UnityWebRequest data = UnityWebRequest.Get(url);

            GameEntry.Http.StartCoroutine(Request(data));
        }
Exemplo n.º 23
0
    IEnumerator Start()
    {
        webViewObject = (new GameObject("WebViewObject")).AddComponent <WebViewObject>();
        webViewObject.Init(
            cb: (msg) =>
        {
            Debug.Log(string.Format("CallFromJS[{0}]", msg));
            status.text = msg;
            status.GetComponent <Animation>().Play();
        },
            err: (msg) =>
        {
            Debug.Log(string.Format("CallOnError[{0}]", msg));
            status.text = msg;
            status.GetComponent <Animation>().Play();
        },
            httpErr: (msg) =>
        {
            Debug.Log(string.Format("CallOnHttpError[{0}]", msg));
            status.text = msg;
            status.GetComponent <Animation>().Play();
        },
            started: (msg) =>
        {
            Debug.Log(string.Format("CallOnStarted[{0}]", msg));
        },
            hooked: (msg) =>
        {
            Debug.Log(string.Format("CallOnHooked[{0}]", msg));
        },
            ld: (msg) =>
        {
            Debug.Log(string.Format("CallOnLoaded[{0}]", msg));
#if UNITY_EDITOR_OSX || (!UNITY_ANDROID && !UNITY_WEBPLAYER && !UNITY_WEBGL)
            // NOTE: depending on the situation, you might prefer
            // the 'iframe' approach.
            // cf. https://github.com/gree/unity-webview/issues/189
#if true
            webViewObject.EvaluateJS(@"
                  if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) {
                    window.Unity = {
                      call: function(msg) {
                        window.webkit.messageHandlers.unityControl.postMessage(msg);
                      }
                    }
                  } else {
                    window.Unity = {
                      call: function(msg) {
                        window.location = 'unity:' + msg;
                      }
                    }
                  }
                ");
#else
            webViewObject.EvaluateJS(@"
                  if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) {
                    window.Unity = {
                      call: function(msg) {
                        window.webkit.messageHandlers.unityControl.postMessage(msg);
                      }
                    }
                  } else {
                    window.Unity = {
                      call: function(msg) {
                        var iframe = document.createElement('IFRAME');
                        iframe.setAttribute('src', 'unity:' + msg);
                        document.documentElement.appendChild(iframe);
                        iframe.parentNode.removeChild(iframe);
                        iframe = null;
                      }
                    }
                  }
                ");
#endif
#elif UNITY_WEBPLAYER || UNITY_WEBGL
            webViewObject.EvaluateJS(
                "window.Unity = {" +
                "   call:function(msg) {" +
                "       parent.unityWebView.sendMessage('WebViewObject', msg)" +
                "   }" +
                "};");
#endif
            webViewObject.EvaluateJS(@"Unity.call('ua=' + navigator.userAgent)");
        }
            //transparent: false,
            //zoom: true,
            //ua: "custom user agent string",
            //// android
            //androidForceDarkMode: 0,  // 0: follow system setting, 1: force dark off, 2: force dark on
            //// ios
            //enableWKWebView: true,
            //wkContentMode: 0,  // 0: recommended, 1: mobile, 2: desktop
            //wkAllowsLinkPreview: true,
            //// editor
            //separated: false
            );
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
        webViewObject.bitmapRefreshCycle = 1;
#endif
        // cf. https://github.com/gree/unity-webview/pull/512
        // Added alertDialogEnabled flag to enable/disable alert/confirm/prompt dialogs. by KojiNakamaru · Pull Request #512 · gree/unity-webview
        //webViewObject.SetAlertDialogEnabled(false);

        // cf. https://github.com/gree/unity-webview/pull/728
        //webViewObject.SetCameraAccess(true);
        //webViewObject.SetMicrophoneAccess(true);

        // cf. https://github.com/gree/unity-webview/pull/550
        // introduced SetURLPattern(..., hookPattern). by KojiNakamaru · Pull Request #550 · gree/unity-webview
        //webViewObject.SetURLPattern("", "^https://.*youtube.com", "^https://.*google.com");

        // cf. https://github.com/gree/unity-webview/pull/570
        // Add BASIC authentication feature (Android and iOS with WKWebView only) by takeh1k0 · Pull Request #570 · gree/unity-webview
        //webViewObject.SetBasicAuthInfo("id", "password");

        //webViewObject.SetScrollbarsVisibility(true);

        webViewObject.SetMargins(5, 100, 5, Screen.height / 4);
        webViewObject.SetTextZoom(100);  // android only. cf. https://stackoverflow.com/questions/21647641/android-webview-set-font-size-system-default/47017410#47017410
        webViewObject.SetVisibility(true);

#if !UNITY_WEBPLAYER && !UNITY_WEBGL
        if (Url.StartsWith("http"))
        {
            webViewObject.LoadURL(Url.Replace(" ", "%20"));
        }
        else
        {
            var exts = new string[] {
                ".jpg",
                ".js",
                ".html"  // should be last
            };
            foreach (var ext in exts)
            {
                var    url    = Url.Replace(".html", ext);
                var    src    = System.IO.Path.Combine(Application.streamingAssetsPath, url);
                var    dst    = System.IO.Path.Combine(Application.persistentDataPath, url);
                byte[] result = null;
                if (src.Contains("://"))    // for Android
                {
#if UNITY_2018_4_OR_NEWER
                    // NOTE: a more complete code that utilizes UnityWebRequest can be found in https://github.com/gree/unity-webview/commit/2a07e82f760a8495aa3a77a23453f384869caba7#diff-4379160fa4c2a287f414c07eb10ee36d
                    var unityWebRequest = UnityWebRequest.Get(src);
                    yield return(unityWebRequest.SendWebRequest());

                    result = unityWebRequest.downloadHandler.data;
#else
                    var www = new WWW(src);
                    yield return(www);

                    result = www.bytes;
#endif
                }
                else
                {
                    result = System.IO.File.ReadAllBytes(src);
                }
                System.IO.File.WriteAllBytes(dst, result);
                if (ext == ".html")
                {
                    webViewObject.LoadURL("file://" + dst.Replace(" ", "%20"));
                    break;
                }
            }
        }
#else
        if (Url.StartsWith("http"))
        {
            webViewObject.LoadURL(Url.Replace(" ", "%20"));
        }
        else
        {
            webViewObject.LoadURL("StreamingAssets/" + Url.Replace(" ", "%20"));
        }
#endif
        yield break;
    }
Exemplo n.º 24
0
    private IEnumerator GetDirection(string geoObjectId, LocationDataModel location)
    {
        if (_authToken == null)
        {
            yield return(new WaitForSeconds(1));
        }

        string requestString            = _serverApiString + "direction";
        var    uriBuilder               = new UriBuilder(requestString);
        NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);

        queryString.Add("lat", location.lat.ToString());
        queryString.Add("lng", location.lng.ToString());
        queryString.Add("objectId", geoObjectId);
        uriBuilder.Query = queryString.ToString();
        // requestString = uriBuilder.ToString();
        requestString += "?" + queryString.ToString();
        UnityWebRequest www = UnityWebRequest.Get(requestString);

        www.SetRequestHeader("Authorization", "Bearer " + _authToken);
        // www.timeout = 4;

        var time = DateTime.Now.Second;

        yield return(www.SendWebRequest());

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError(requestString);
            Debug.LogError(www.error);
            Debug.LogError(www.result);
            Debug.LogError(www.downloadHandler.text);
            displayDropdownMessage.text = "До данного объекта не получается проложить маршрут";
            yield break;
        }

        var elapsedTime = DateTime.Now.Second - time;

        Debug.Log("Elapsed time " + elapsedTime.ToString());
        string responseText = www.downloadHandler.text;

        ResponseFromServerOneToOneDirectionModel response = null;

        try
        {
            response = JsonConvert.DeserializeObject <ResponseFromServerOneToOneDirectionModel>(responseText);
        }
        catch (Exception e)
        {
            Debug.LogError(e);
            yield break;
        }

        Debug.Log(response);


        List <Step>    steps        = response.message._steps;
        List <Vector3> vector3Steps = new List <Vector3>();

        foreach (var step in steps)
        {
            vector3Steps.Add(GPSEncoder.GPSToUCS(step.lat,
                                                 step.lng));
        }

        if (steps.Count == 1)
        {
            var gameObject = _gpsPlacingBehaviour.GetGameObjectOfGeoObjectInSceneById(geoObjectId);

            vector3Steps.Add(gameObject.transform.position);
        }

        vector3Steps[0] = _mainCamera.transform.position;

        SetupDirectionObject(vector3Steps);
    }
Exemplo n.º 25
0
        /// <summary>
        /// Get the latest content from the web site at most once every 24 hours
        /// </summary>
        /// <returns>Enumerator</returns>
        IEnumerator GetRemoteUpdate()
        {
#if UNITY_2018_3_OR_NEWER
            using (UnityWebRequest www = UnityWebRequest.Get(URL))
            {
                yield return(www.SendWebRequest());

                if (www.isNetworkError || www.isHttpError)
                {
                    Debug.Log(www.error);
                }
                else
                {
                    try
                    {
                        string result = www.downloadHandler.text;
#else
            using (WWW www = new WWW(URL))
            {
                while (!www.isDone)
                {
                    yield return(www);
                }

                if (!string.IsNullOrEmpty(www.error))
                {
                    Debug.Log(www.error);
                }
                else
                {
                    try
                    {
                        string result = www.text;
#endif
                        int first = result.IndexOf("####");
                        if (first > 0)
                        {
                            result = result.Substring(first + 10);
                            first  = result.IndexOf("####");
                            if (first > 0)
                            {
                                result = result.Substring(0, first);
                                result = result.Replace("<br />", "");
                                result = result.Replace("&#8221;", "\"");
                                result = result.Replace("&#8220;", "\"");
                                m_downloadCompleteCallback(JsonUtility.FromJson <PWMessage>(result));

                                //Debug.Log(result);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.Log(e.Message);
                    }
                }
            }
            m_updateCoroutine = null;
        }
    }
}
Exemplo n.º 26
0
        private IEnumerator Load <T>(string url, string pathWithoutHash, string hash, string storePath, Func <byte[], T> bytesToTConverter, Action <T> onLoaded, Action <int, string> onLoadFailed, Dictionary <string, string> requestHeader = null) where T : UnityEngine.Object
        {
            // ファイルパス、ファイル名を生成する
            var targetFolderNameAndHash = GenerateFolderAndFilePath(pathWithoutHash, hash, storePath);
            var targetFolderName        = targetFolderNameAndHash.url;
            var targetFileName          = targetFolderNameAndHash.url + "_" + targetFolderNameAndHash.hash;

            // フォルダ、ファイルがあるかどうかチェックする
            var folderPath       = Path.Combine(storePath, targetFolderName);
            var existFolderPaths = filePersist.FileNamesInDomain(folderPath);

            var fileUniquePath = Path.Combine(folderPath, targetFileName);

            // キャッシュに対象が存在するかどうか
            if (pathObjectCache.ContainsKey(fileUniquePath))
            {
                var cached = pathObjectCache[fileUniquePath] as T;
                onLoaded(cached);
                yield break;
            }

            // もしすでにロード中だったら待機する
            if (cachingLock.ContainsKey(targetFolderName))
            {
                while (cachingLock.ContainsKey(targetFolderName))
                {
                    yield return(null);
                }

                // 待機完了、オンメモリのキャッシュにあるかどうかチェックし、あれば返す。なければダウンロードに移行する。

                UnityEngine.Object _object;
                if (pathObjectCache.TryGetValue(fileUniquePath, out _object))
                {
                    onLoaded(_object as T);
                    yield break;
                }

                // ダウンロードに向かう。
            }

            // 処理中のロックをかける
            lock (writeLock)
            {
                cachingLock.Add(targetFolderName, CONST_VALUE);
            }

            /*
             *  ロック後に、オンメモリにロードする必要 or DLする必要のチェックを行う。
             */

            // 既にDL済みのファイルが一つ以上存在していて、hashもヒットした -> ファイルはまだオンメモリにはないので、ここでロードして返す。
            if (0 < existFolderPaths.Length && filePersist.IsExist(folderPath, targetFileName))
            {
                // byte列を非同期で読み出す
                filePersist.Load(
                    folderPath,
                    targetFileName,
                    bytes =>
                {
                    // 読み出し成功したのでオンメモリに載せる。
                    var tObj = bytesToTConverter(bytes);

                    pathObjectCache[fileUniquePath] = tObj;
                    lock (writeLock)
                    {
                        cachingLock.Remove(targetFolderName);
                    }

                    onLoaded(tObj);
                },
                    error =>
                {
                    lock (writeLock)
                    {
                        cachingLock.Remove(targetFolderName);
                    }
                    onLoadFailed(0, error);
                }
                    );
                yield break;
            }

            // オンメモリ、ファイルとしても手元に存在しないので、DLして取得を行う。

            // 求めるhashに合致しない古いキャッシュファイルがある場合、消す。
            foreach (var path in existFolderPaths)
            {
                var fileName = Path.GetFileName(path);
                filePersist.Delete(folderPath, fileName);
            }

            // ダウンロードを行う。
            using (var request = UnityWebRequest.Get(url))
            {
                filePersist.CreateDirectory(Path.Combine(filePersist.basePath, folderPath));
                var fileSavePath = Path.Combine(filePersist.basePath, folderPath, targetFileName);

                if (requestHeader == null)
                {
                    requestHeader = new Dictionary <string, string>();
                }

                foreach (var item in requestHeader)
                {
                    request.SetRequestHeader(item.Key, item.Value);
                }

                var handler = new DownloadHandlerFile(fileSavePath);

                // 失敗時に中途半端なファイルを消す
                handler.removeFileOnAbort = true;
                request.downloadHandler   = handler;

                request.timeout = 5;

                var p = request.SendWebRequest();

                while (!p.isDone)
                {
                    yield return(null);
                }

                var responseCode = (int)request.responseCode;

                if (request.isNetworkError)
                {
                    filePersist.Delete(folderPath, targetFileName);
                    lock (writeLock)
                    {
                        cachingLock.Remove(targetFolderName);
                    }
                    onLoadFailed(responseCode, request.error);
                    yield break;
                }

                if (request.isHttpError)
                {
                    filePersist.Delete(folderPath, targetFileName);
                    lock (writeLock)
                    {
                        cachingLock.Remove(targetFolderName);
                    }
                    onLoadFailed(responseCode, request.error);
                    yield break;
                }
            }

            // ダウンロードが成功、保存も完了

            // 保存したデータのbyte列を非同期で読み出す
            filePersist.Load(
                folderPath,
                targetFileName,
                bytes =>
            {
                // 型に対しての返還式を取り出し、byteからT型を生成する。
                var obj = bytesToTConverter(bytes);

                // キャッシュを行う
                pathObjectCache[fileUniquePath] = obj;

                lock (writeLock)
                {
                    cachingLock.Remove(targetFolderName);
                }

                // 取得したT型オブジェクトを返す
                onLoaded(obj);
            },
                error =>
            {
                lock (writeLock)
                {
                    cachingLock.Remove(targetFolderName);
                }
                onLoadFailed(0, error);
            }
                );
        }
Exemplo n.º 27
0
        IEnumerator Fetch(float delayRequest)
        {
            yield return(new WaitForSeconds(delayRequest));

            CloseGroup();

            bool shouldRetry = false;
            int  retryCount  = 0;

            string url = API_URL_ASSETS + requestUrl;

            do
            {
                using (UnityWebRequest request = UnityWebRequest.Get(url))
                {
                    if (OpenSeaRequestController.VERBOSE)
                    {
                        Debug.Log($"RequestGroup: Request to OpenSea {url}");
                    }
                    yield return(request.SendWebRequest());

                    AssetsResponse response = null;

                    if (!request.isNetworkError && !request.isHttpError)
                    {
                        response = Utils.FromJsonWithNulls <AssetsResponse>(request.downloadHandler.text);
                    }

                    if (OpenSeaRequestController.VERBOSE)
                    {
                        Debug.Log($"RequestGroup: Request resolving {response != null} {request.error} {url}");
                    }
                    if (response != null)
                    {
                        shouldRetry = false;
                        using (var iterator = requests.GetEnumerator())
                        {
                            while (iterator.MoveNext())
                            {
                                iterator.Current.Value.Resolve(response);
                            }
                        }
                    }
                    else
                    {
                        shouldRetry = retryCount < REQUEST_RETRIES;
                        if (!shouldRetry)
                        {
                            using (var iterator = requests.GetEnumerator())
                            {
                                while (iterator.MoveNext())
                                {
                                    iterator.Current.Value.Resolve(request.error);
                                }
                            }
                        }
                        else
                        {
                            retryCount++;
                            if (OpenSeaRequestController.VERBOSE)
                            {
                                Debug.Log($"RequestGroup: Request retrying {url}");
                            }
                            yield return(new WaitForSeconds(GetRetryDelay()));
                        }
                    }
                }
            } while (shouldRetry);
        }
Exemplo n.º 28
0
        protected virtual IEnumerator LoadImage(string rootPath, Image image, int imageID)
        {
            if (_assetCache.ImageCache[imageID] == null)
            {
                Texture2D texture = null;
                if (image.Uri != null)
                {
                    var uri = image.Uri;

                    Regex regex = new Regex(Base64StringInitializer);
                    Match match = regex.Match(uri);
                    if (match.Success)
                    {
                        var base64Data  = uri.Substring(match.Length);
                        var textureData = Convert.FromBase64String(base64Data);
                        texture = new Texture2D(0, 0);
                        texture.LoadImage(textureData);
                    }
                    else if (_loadType == LoadType.Uri)
                    {
                        var www = UnityWebRequest.Get(Path.Combine(rootPath, uri));
                        www.downloadHandler = new DownloadHandlerTexture();

                        yield return(www.Send());

                        // HACK to enable mipmaps :(
                        var tempTexture = DownloadHandlerTexture.GetContent(www);
                        if (tempTexture != null)
                        {
                            texture = new Texture2D(tempTexture.width, tempTexture.height, tempTexture.format, true);
                            texture.SetPixels(tempTexture.GetPixels());
                            texture.Apply(true);
                        }
                        else
                        {
                            Debug.LogFormat("{0} {1}", www.responseCode, www.url);
                            texture = new Texture2D(16, 16);
                        }
                    }
                    else if (_loadType == LoadType.Stream)
                    {
                        var    pathToLoad = Path.Combine(rootPath, uri);
                        var    file       = File.OpenRead(pathToLoad);
                        byte[] bufferData = new byte[file.Length];
                        file.Read(bufferData, 0, (int)file.Length);
#if !WINDOWS_UWP
                        file.Close();
#else
                        file.Dispose();
#endif
                        texture = new Texture2D(0, 0);
                        texture.LoadImage(bufferData);
                    }
                }
                else
                {
                    texture = new Texture2D(0, 0);
                    var bufferView = image.BufferView.Value;
                    var buffer     = bufferView.Buffer.Value;
                    var data       = new byte[bufferView.ByteLength];

                    var bufferContents = _assetCache.BufferCache[bufferView.Buffer.Id];
                    System.Buffer.BlockCopy(bufferContents, bufferView.ByteOffset, data, 0, data.Length);
                    texture.LoadImage(data);
                }

                _assetCache.ImageCache[imageID] = texture;
            }
        }
Exemplo n.º 29
0
    public IEnumerator Communicate()
    {
        //yield return StartCoroutine(Draw());

        //Debug.Log("Replay Finished");
        ScreenCapture.CaptureScreenshot(filepath);
        // Wait for seconds to ensure the shot was stored.
        StartCoroutine(Wait());

        byte[] image = GetImageAsByteArray(filepath);
        Debug.Log(endpoint + uriBase + extraPara);
        send        = UnityWebRequest.Put(endpoint + uriBase + extraPara, image);
        send.method = UnityWebRequest.kHttpVerbPOST;
        //send.downloadHandler = new DownloadHandlerBuffer();
        send.SetRequestHeader("Content-Type", "application/octet-stream");
        send.SetRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
        //send.uploadHandler.contentType = "application/octet-stream";

        yield return(send.SendWebRequest());

        string response = send.GetResponseHeader("Operation-Location");

        Debug.Log("Send: method: " + send.method);
        Debug.Log("Send uri: " + send.uri);
        Debug.Log("Content-Type: " + send.GetRequestHeader("Content-Type"));
        Debug.Log("response: " + response);
        Debug.Log("Processing...");
        //trackMgmt.Clear_All();
        sceneMgmt.EraseAll();
        box.SetActive(true);

        yield return(new WaitForSeconds(10f));

        get        = UnityWebRequest.Get(response);
        get.method = UnityWebRequest.kHttpVerbGET;
        get.SetRequestHeader("Content-Type", "application/octet-stream");
        get.SetRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
        //get.uploadHandler.contentType = "application/octet-stream";
        Debug.Log("Get uri: " + get.uri);
        yield return(get.SendWebRequest());

        float score = 0f;

        // If error occurs, use local evaluation algorithm instead.
        if (get.isNetworkError == true)
        {
            Debug.Log("NetworkError");
            score = Evaluate();
        }
        else if (get.isHttpError == true)
        {
            Debug.Log("HttpError");
            score = Evaluate();
        }
        else
        {
            Debug.Log("Success");
            Debug.Log(get.downloadHandler.text);
            File.WriteAllText(path + ".json", get.downloadHandler.text);
            //JsonData result = JsonMapper.ToObject(send.downloadHandler.text);
            analyzed = Decom(get.downloadHandler.text);
            Debug.Log("Word Count: " + analyzed.Count);
            score = ResultEvaluate();
            //for (int i = 0; i < analyzed.Count; i++)
            //{
            //    Debug.Log("Ana: " + analyzed[i]);
            //}
            //Debug.Log(result);
        }
        if (File.Exists(scorepath))
        {
            File.Delete(scorepath);
            //Debug.Log("Deleted");
        }
        File.WriteAllText(scorepath, score.ToString());
        box.SetActive(false);
        // Back to student page
        sceneLoad.LoadScence(24);
    }
Exemplo n.º 30
0
    IEnumerator getOrders()
    {
        if (continueRequest)
        {
            yield break;
        }
        continueRequest = true;
        float          RequestFrequencyInSecond = 5f; //update after every 5 second
        WaitForSeconds WaitTime = new WaitForSeconds(RequestFrequencyInSecond);

        while (continueRequest)
        {
            var _request = UnityWebRequest.Get("http://192.168.2.177/api/plant/lucasnuelle/" + "?t=" + getUTCTime());
            //	Disable cache on the client side
            _request.SetRequestHeader("Cache-Control", "max-age=0, no-cache, no-store");
            _request.SetRequestHeader("Pragma", "no-cache");
            yield return(_request.SendWebRequest());

            if (_request.isNetworkError)
            {
                Debug.Log("Error: " + _request.error);
            }
            else
            {
                var result = _request.downloadHandler.text;
                Debug.Log("Received " + result);
                parseData = JsonUtility.FromJson <SegmentCollection>(result);
                Debug.Log("size: " + parseData.segments.Length);                  //get the length of the all segments	:8
                for (int i = 0; i < parseData.segments.Length; i++)
                {
                    if (parseData.segments[i].identifier.Contains("IMS1"))
                    {
                        string IMS3StateOutput      = parseData.segments[i].state_name;
                        string IMS3IdentifierOutput = parseData.segments[i].identifier;
                        Debug.Log("State Name: " + IMS3IdentifierOutput);                      //display the identifier
                        Debug.Log("Machine state: " + IMS3StateOutput);                        //display the state name
                        gameObject.GetComponent <demoIoT>().IMS3Valtext        = IMS3StateOutput;
                        gameObject.GetComponent <demoIoT>().IMS3StationValtext = IMS3IdentifierOutput;
                    }
                    if (parseData.segments[i].identifier.Contains("IMS3A"))
                    {
                        string IMS3AStateOutput      = parseData.segments[i].state_name;
                        string IMS3AIdentifierOutput = parseData.segments[i].identifier;

                        Debug.Log("State Name: " + IMS3AIdentifierOutput);                          //display the identifier
                        Debug.Log("Machine state: " + IMS3AStateOutput);
                        gameObject.GetComponent <demoIoT>().IMS3AValtext        = IMS3AStateOutput;
                        gameObject.GetComponent <demoIoT>().IMS3AStationValtext = IMS3AIdentifierOutput;
                    }
                    if (parseData.segments[i].identifier.Contains("IMS3B"))
                    {
                        string IMS3BStateOutput      = parseData.segments[i].state_name;
                        string IMS3BIdentifierOutput = parseData.segments[i].identifier;

                        Debug.Log("State Name: " + IMS3BIdentifierOutput);                          //display the identifier
                        Debug.Log("Machine state: " + IMS3BStateOutput);
                        gameObject.GetComponent <demoIoT>().IMS3BValtext        = IMS3BStateOutput;
                        gameObject.GetComponent <demoIoT>().IMS3BStationValtext = IMS3BIdentifierOutput;
                    }
                    if (parseData.segments[i].identifier.Contains("IMS4A"))
                    {
                        string IMS4AStateOutput      = parseData.segments[i].state_name;
                        string IMS4AIdentifierOutput = parseData.segments[i].identifier;

                        Debug.Log("State Name: " + IMS4AIdentifierOutput);                          //display the identifier
                        Debug.Log("Machine state: " + IMS4AStateOutput);
                        gameObject.GetComponent <demoIoT>().IMS4AValtext        = IMS4AStateOutput;
                        gameObject.GetComponent <demoIoT>().IMS4AStationValtext = IMS4AIdentifierOutput;
                    }
                    if (parseData.segments[i].identifier.Contains("IMS4B"))
                    {
                        string IMS4BStateOutput      = parseData.segments[i].state_name;
                        string IMS4BIdentifierOutput = parseData.segments[i].identifier;

                        Debug.Log("State Name: " + IMS4BIdentifierOutput);                          //display the identifier
                        Debug.Log("Machine state: " + IMS4BStateOutput);
                        gameObject.GetComponent <demoIoT>().IMS4BValtext        = IMS4BStateOutput;
                        gameObject.GetComponent <demoIoT>().IMS4BStationValtext = IMS4BIdentifierOutput;
                    }
                    if (parseData.segments[i].identifier.Contains("IMS5A"))
                    {
                        string IMS5AStateOutput      = parseData.segments[i].state_name;
                        string IMS5AIdentifierOutput = parseData.segments[i].identifier;

                        Debug.Log("State Name: " + IMS5AIdentifierOutput);                          //display the identifier
                        Debug.Log("Machine state: " + IMS5AStateOutput);
                        gameObject.GetComponent <demoIoT>().IMS5AValtext        = IMS5AStateOutput;
                        gameObject.GetComponent <demoIoT>().IMS5AStationValtext = IMS5AIdentifierOutput;
                    }
                    if (parseData.segments[i].identifier.Contains("IMS5B"))
                    {
                        string IMS5BStateOutput      = parseData.segments[i].state_name;
                        string IMS5BIdentifierOutput = parseData.segments[i].identifier;

                        Debug.Log("State Name: " + IMS5BIdentifierOutput);                          //display the identifier
                        Debug.Log("Machine state: " + IMS5BStateOutput);
                        gameObject.GetComponent <demoIoT>().IMS5BValtext        = IMS5BStateOutput;
                        gameObject.GetComponent <demoIoT>().IMS5BStationValtext = IMS5BIdentifierOutput;
                    }
                    if (parseData.segments[i].identifier.Contains("IMS7"))
                    {
                        string IMS7StateOutput      = parseData.segments[i].state_name;
                        string IMS7IdentifierOutput = parseData.segments[i].identifier;

                        Debug.Log("State Name: " + IMS7IdentifierOutput);                          //display the identifier
                        Debug.Log("Machine state: " + IMS7StateOutput);
                        gameObject.GetComponent <demoIoT>().IMS7Valtext        = IMS7StateOutput;
                        gameObject.GetComponent <demoIoT>().IMS7StationValtext = IMS7IdentifierOutput;
                    }
                }
            }
        }
        yield return(WaitTime);       //Wait for request FrequencyInsec time
    }