public static Instance ( ) : UnityMainThreadDispatcher, | ||
return | UnityMainThreadDispatcher, |
//void ballL void runQueueTickBased() { if (SpawnListQueue.Count > 0) { Queue <IEnumerator> tempQueue = SpawnListQueue.Dequeue(); while (tempQueue.Count > 0) { UnityMainThreadDispatcher.Instance().Enqueue(tempQueue.Dequeue()); } } else { Debug.Log("No item to Run!"); } Debug.Log("tap"); }
public void enableCAGCallback(byte ID, object Data) { byte[] groupIDs = (byte[])Data; int idx; for (int i = groupIDs.Length - 1; i >= 0; i--) { idx = (int)groupIDs[i]; if (AGXPresent) { UnityMainThreadDispatcher.Instance().Enqueue(() => AGXActivateGroupDelayCheck(idx, true)); } else { UnityMainThreadDispatcher.Instance().Enqueue(() => FlightGlobals.ActiveVessel.ActionGroups.SetGroup(ActionGroupIDs[idx], true)); } } }
protected override void Client_MatchCreated(Match match) { base.Client_MatchCreated(match); if (TournamentMode && match.Players.Contains(Plugin.client.SelfObject)) { Match = match; UnityMainThreadDispatcher.Instance().Enqueue(() => { //Player shouldn't be able to back out of a coordinated match var screenSystem = this.GetField <ScreenSystem>("_screenSystem", typeof(FlowCoordinator)); screenSystem.GetField <Button>("_backButton").interactable = false; _splashScreen.StatusText = "Match has been created. Waiting for coordinator to select a song."; }); } }
public static void NewFile(NetworkFile file) { file.Start += delegate(NetworkFile thisfile) { UnityMainThreadDispatcher.Instance().Enqueue(delegate() { SocketFile newobject = Instantiate(Preset.objects.SocketFile, Preset.objects.SocketFileGrid.transform); newobject.Set(thisfile); Preset.objects.SocketFileGrid.repositionNow = true; }); }; file.End += delegate(NetworkFile thisfile) { UnityMainThreadDispatcher.Instance().Enqueue(delegate() { DestroyImmediate(SocketFile.Items[thisfile].gameObject); Preset.objects.SocketFileGrid.repositionNow = true; }); }; }
protected override void Client_LoadedSong(IBeatmapLevel level) { base.Client_LoadedSong(level); if (Plugin.IsInMenu()) { UnityMainThreadDispatcher.Instance().Enqueue(() => { //If the player is still on the results screen, go ahead and boot them out if (_resultsViewController.isInViewControllerHierarchy) { resultsViewController_continueButtonPressedEvent(null); } songSelection_SongSelected(level.levelID); }); } }
void JobAction(CaptureJob job) { try { AssignSlot(job); UnityMainThreadDispatcher.Instance().Enqueue(() => { var shield = AssetBundlesLoader.GenerateRandomShield(new Vector3(SpawnX, SpawnY + job.slotIndex * SpacingPerCamera, SpawnZ), job.slotIndex); //Save shield selection File.WriteAllText($"{job.UserId}.shield", JsonUtility.ToJson(shield)); GifCaptureManagers[job.slotIndex].StartCapturing(job); }); } catch (Exception) { job.Status = CaptureJobStatus.Error; } }
private async void SubmitScoreWhenResolved(string username, ulong userId, LevelCompletionResults results) { var scores = ((await HostScraper.RequestResponse(EventHost, new Packet(new SubmitScore { Score = new Score { EventId = Event.EventId, Parameters = _currentParameters, UserId = userId, Username = username, FullCombo = results.fullCombo, _Score = results.modifiedScore, Color = "#ffffff" } }), typeof(ScoreRequestResponse), username, userId)).SpecificPacket as ScoreRequestResponse).Scores.Take(10).ToArray(); UnityMainThreadDispatcher.Instance().Enqueue(() => SetCustomLeaderboardScores(scores, userId)); }
void EmitTelemetry(SocketIOEvent obj) { UnityMainThreadDispatcher.Instance().Enqueue(() => //new thread { print("Attempting to Send..."); // send only if it's not being manually driven if ((Input.GetKey(KeyCode.W)) || (Input.GetKey(KeyCode.S))) { _socket.Emit("telemetry", new JSONObject()); } else { // Collect Data from the Car Dictionary <string, string> data = new Dictionary <string, string>(); data["steering_angle"] = _carController.CurrentSteerAngle.ToString("N4"); data["throttle"] = _carController.AccelInput.ToString("N4"); data["speed"] = _carController.CurrentSpeed.ToString("N4"); data["image"] = Convert.ToBase64String(CameraHelper.CaptureFrame(FrontFacingCamera)); _socket.Emit("telemetry", new JSONObject(data)); } }); // UnityMainThreadDispatcher.Instance().Enqueue(() => // { // // // // // send only if it's not being manually driven // if ((Input.GetKey(KeyCode.W)) || (Input.GetKey(KeyCode.S))) { // _socket.Emit("telemetry", new JSONObject()); // } // else { // // Collect Data from the Car // Dictionary<string, string> data = new Dictionary<string, string>(); // data["steering_angle"] = _carController.CurrentSteerAngle.ToString("N4"); // data["throttle"] = _carController.AccelInput.ToString("N4"); // data["speed"] = _carController.CurrentSpeed.ToString("N4"); // data["image"] = Convert.ToBase64String(CameraHelper.CaptureFrame(FrontFacingCamera)); // _socket.Emit("telemetry", new JSONObject(data)); // } // // // // }); }
public void Patient_signup() { try { FirebaseController.instance.signup(Email.text, password.text, _name.text, new System.DateTime(getValue(year), getValue(month), getValue(day)), disease.text, getDoctorID(), task => { if (task.IsCanceled || task.IsFaulted) { UnityMainThreadDispatcher.Instance().Enqueue(() => { Debug.LogError("sign up Error"); ErrorPopup.SetActive(true); return; }); } }, callback => { if (callback.IsCanceled || callback.IsFaulted) { UnityMainThreadDispatcher.Instance().Enqueue(() => { Debug.LogError("sign up Error"); ErrorPopup.SetActive(true); return; }); } if (callback.IsCompleted) { UnityMainThreadDispatcher.Instance().Enqueue(() => { SceneManager.LoadScene(2); }); } }); } catch { UnityMainThreadDispatcher.Instance().Enqueue(() => { Debug.LogError("sign up Error"); ErrorPopup.SetActive(true); return; }); } }
// Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.Space)) { var audioSource = gameObject.GetComponent <AudioSource>(); AudioClip clip = null; string link = "http://localhost:64987/files/posted/04d5cd42-2e6c-4e5c-8724-37d92eb40cce.mp3.ogg"; UnityMainThreadDispatcher.Instance().Enqueue(() => { //UnityWebRequest uwr = new UnityWebRequest(link); //var data = uwr.downloadHandler.data; //AudioClip clip2 = AudioClip.Create( new AudioClip(); WWW www1 = new WWW(link); clip = www1.GetAudioClip(false, true, AudioType.OGGVORBIS); //if (clip.isReadyToPlay) { audioSource.clip = clip; audioSource.Play(); } }); //bool isReadyToPlay = false; //while (clip != null && !isReadyToPlay) //{ // UnityMainThreadDispatcher.Instance().Enqueue(() => // { // isReadyToPlay = clip.isReadyToPlay; // }); // if (isReadyToPlay) // { // UnityMainThreadDispatcher.Instance().Enqueue(() => // { // audioSource.clip = clip; // audioSource.Play(); // }); // } //} } }
/// <summary> /// Trigger a simulation step /// </summary> void Step() { UnityMainThreadDispatcher.Instance().Enqueue(() => { // Trigger the phyics simulation Physics.Simulate(deltaTime); // Compute the perceptions for all bodies if they have a perceiver component foreach (var agentBody in BodiesRepository.Instance().Bodies) { var perceiver = agentBody.Value.GetComponent(typeof(Perceiver)) as Perceiver; if (perceiver != null) { var perceptions = perceiver.PerceivedObjets; this.sarlInterface.EmitPerceptions(new PerceptionList(agentBody.Key, perceptions)); } } }); }
public BotConnection(string ip, string puerto, System.Action callback, float vel) { esperandoJugada = false; _velocidad = vel; socket = new WebSocket("ws://" + ip + ":" + puerto); socket.OnMessage += (sender, e) => { if (esperandoJugada) { UnityMainThreadDispatcher.Instance().Enqueue(realizarJugada(JsonUtility.FromJson <Jugada>(e.Data))); } }; socket.OnOpen += (sender, e) => { callback(); }; socket.Connect(); }
/// <summary> /// When the server is offline or we can't reach him just quit and notify the player /// </summary> private void OnServerOffline(NetworkMessage netMsg) { UnityMainThreadDispatcher.Instance().Enqueue(() => { Debug.Log("If we got disconnect here means the server is offline because we have no session "); var m = new Modal("Server is offline", "Servers are under maintenance or offline", Modal.Type.Information); m.AddCloseListener(delegate { Destroy(m.GetReference()); #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #else Application.Quit(); #endif }); m.Render(); }); }
/// <summary> /// Called when the server returns Login Success opcode /// </summary> /// <param name="netMsg"></param> protected void OnLoginSuccess(NetworkMessage netMsg) { UnityMainThreadDispatcher.Instance().Enqueue(() => { LoginPanel.SetActive(false); if (GameObject.Find("LoadingBox") != null) { Destroy(GameObject.Find("LoadingBox")); } //Create a spinner var spin = Instantiate(Resources.Load <GameObject>("Prefabs/Modals/LoadingBox"), UI.transform) as GameObject; spin.name = "LoadingBox"; spin.transform.Find("Text").GetComponent <Text>().text = "Loading Profile.."; //Read profileData var profileData = netMsg.ReadMessage <ProfileData>(); //We make observer for WhenData arrives in order to define dynamiclly when loading or loaded is done spin.transform.Find("Text").GetComponent <Text>().text = "Loading Cards.."; SocketController.Send(NetworkInstructions.PLAYER_CARDS_REQUEST, null); //Save the username and pwd if the remmeber is set true if (PlayerPrefs.GetInt("login_remmeber") == 1) { PlayerPrefs.SetString("login_username", usrField.text); PlayerPrefs.SetString("login_password", pwdField.text); Debug.Log("Remmeber saved"); } //Unbind the login handlers since we're going to load the next scene SocketController.UnbindEvent(NetworkInstructions.LOGIN_FAIL); SocketController.UnbindEvent(NetworkInstructions.LOGIN_REQUEST); SocketController.UnbindEvent(NetworkInstructions.LOGIN_SUCCESS); //Wipe notifier list if it gives problems trying to notify here SocketController.UnbindEvent(NetworkInstructions.ServerOffline); //Load next scene SceneManager.LoadSceneAsync("MainMenu"); }); }
public void ListFoodItems() { FirebaseDatabase.DefaultInstance.GetReference("/restaurants/" + newUser.UserId + "/Menu").GetValueAsync().ContinueWith(task => { if (task.IsFaulted) { // Handle the error... } else if (task.IsCompleted) { DataSnapshot snapshot = task.Result; foreach (DataSnapshot subInfo in snapshot.Children) { UnityMainThreadDispatcher.Instance().Enqueue(InstantiateItemList(subInfo)); } UnityMainThreadDispatcher.Instance().Enqueue(LoadingFinishedForItemList()); } }); }
public void ListScenes(string bearer) { _bearer = bearer; ForgeLoader forgeLoader = loader.GetComponent <ForgeLoader> (); string url = ForgeLoaderConstants._endpoint1 + forgeLoader.URN + "/scenes"; Hashtable headers = new Hashtable(); headers.Add("Authorization", "Bearer " + _bearer); RestClient rest = new RestClient(new System.Uri(url), headers); rest.FireRequest( (object sender, AsyncCompletedEventArgs args) => { if (args == null || args.UserState == null) { return; } if (args.Error != null) { UnityMainThreadDispatcher.Instance().Enqueue(() => { Debug.Log(Autodesk.Forge.ARKit.ForgeLoader.GetCurrentMethod() + " " + args.Error.Message); }); return; } DownloadDataCompletedEventArgs args2 = args as DownloadDataCompletedEventArgs; string textData = System.Text.Encoding.UTF8.GetString(args2.Result); scenesList = JSON.Parse(textData); if (scenesList.AsArray.Count > 0) { UnityMainThreadDispatcher.Instance().Enqueue(() => { Dropdown dd = combobox.GetComponent <Dropdown> (); foreach (JSONNode child in scenesList.AsArray) { dd.options.Add(new Dropdown.OptionData(child.Value)); } combobox.SetActive(true); }); } } ); }
public virtual void RewardOnClose() { #if UNITY_IPHONE if (rewardEvent == AdEvent.Success) { UnityMainThreadDispatcher.Instance().Enqueue(() => { onRewardShowSuccess?.Invoke(AdEvent.Success); onRewardShowSuccess = null; }); } #else //Android --> onRewardShowSuccess onSuccess Event #endif PauseApp(false); rewardEvent = AdEvent.Load; RewardLoad(); }
void OnMessageHandler(object sender, MessageEventArgs e) { string message = "Court WebSocket server said: " + e.Data; Debug.Log(message); string jsonString = System.Text.Encoding.UTF8.GetString(e.RawData); SocketEntity entity = JsonUtility.FromJson <SocketEntity>(jsonString); if (entity.data.bid > 0) { if (OnBallPositionChanged != null) { string bid = entity.data.bid + ""; int x = entity.data.y; int y = entity.data.x; int z = entity.data.z; UnityMainThreadDispatcher.Instance().Enqueue( () => OnBallPositionChanged(bid, x, y, z) ); } } else if (entity.data.pid > 0) { if (OnPlayerPositionChanged != null) { string pid = entity.data.pid + ""; int x = entity.data.y; int y = entity.data.x; int z = entity.data.z; UnityMainThreadDispatcher.Instance().Enqueue( () => OnPlayerPositionChanged(pid, x, y, z) ); } if (entity.data.shot != null && entity.data.shot.hid != null && OnShotMade != null) { Debug.LogWarning("============== " + entity.data.shot.hid + "........" + entity.data.shot.st); UnityMainThreadDispatcher.Instance().Enqueue( () => OnShotMade(entity.data.shot.hid, entity.data.shot.st) ); } } }
public virtual void OnLobbyStateChange(LobbyState state) { UnityMainThreadDispatcher.Instance().Enqueue(() => { UpdateStartGameButton(); UpdateReadyButton(); UpdatePlayButton(); UpdateControls(); UpdatePlayerStates(); // Emulate clicking a play button if (state == LobbyState.GameInProgress && AutoJoinGameWhenReady && !_wasGameRunningWhenOpened) { OnPlayClick(); } }); }
public async Task PostSave(IHttpContext context, PostSavePayload body) { Authenticator.VerifyAuth(context); if (body == null) { throw new BadRequestException("A body with a fileName must be specified."); } if (body.fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { throw new BadRequestException("Filename contains invalid characters."); } string worldDirectory = Path.Combine(XmlSaveLoad.CheckFiles(), "saves/" + body.fileName); UnityMainThreadDispatcher.Instance().Enqueue(XmlSaveLoad.Instance.ForceWriteWorld(worldDirectory)); await context.SendResponse(HttpStatusCode.OK, body); }
void OnCamConfig(JSONObject json) { float fov = float.Parse(json.GetField("fov").str, CultureInfo.InvariantCulture.NumberFormat); float offset_x = float.Parse(json.GetField("offset_x").str, CultureInfo.InvariantCulture.NumberFormat); float offset_y = float.Parse(json.GetField("offset_y").str, CultureInfo.InvariantCulture.NumberFormat); float offset_z = float.Parse(json.GetField("offset_z").str, CultureInfo.InvariantCulture.NumberFormat); float rot_x = float.Parse(json.GetField("rot_x").str, CultureInfo.InvariantCulture.NumberFormat); float fish_eye_x = float.Parse(json.GetField("fish_eye_x").str, CultureInfo.InvariantCulture.NumberFormat); float fish_eye_y = float.Parse(json.GetField("fish_eye_y").str, CultureInfo.InvariantCulture.NumberFormat); int img_w = int.Parse(json.GetField("img_w").str); int img_h = int.Parse(json.GetField("img_h").str); int img_d = int.Parse(json.GetField("img_d").str); string img_enc = json.GetField("img_enc").str; if (carObj != null) { UnityMainThreadDispatcher.Instance().Enqueue(SetCamConfig(fov, offset_x, offset_y, offset_z, rot_x, img_w, img_h, img_d, img_enc, fish_eye_x, fish_eye_y)); } }
public override IRtmChannel JoinChannel(string channelName) { channelMessageCallback = new RtmWrapperDll.ChannelMessageReceivedHandler(ChannelMessageHandler); leaveCallback = new RtmWrapperDll.LeaveHandler(LeaveChannelHandler); getMembersCallback = new RtmWrapperDll.GetMembersHandler(GetChannelMembersHandler); var channel = RtmWrapperDll.createChannel(channelName, (mid, status) => { Debug.Log("message " + mid + " sent with status: " + status); }, () => { UnityMainThreadDispatcher.Instance().Enqueue(() => { channels.Add(channelName); Debug.Log("joined: " + channelName); OnJoinSuccessCallback(); }); }, (errorCode) => { Debug.Log("error joining channel: " + errorCode); }, channelMessageCallback, leaveCallback, getMembersCallback ); channel.Join(); return(channel); }
protected virtual void Client_ConnectedToServer(ConnectResponse response) { //In case this coordiator is reused, re-set the dismiss-on-disconnect flag ShouldDismissOnReturnToMenu = false; //When we're connected to the server, we should update our self to show our mod list (Plugin.client.Self as Player).ModList = IPA.Loader.PluginManager.EnabledPlugins.Select(x => x.Id).ToArray(); Plugin.client.UpdatePlayer(Plugin.client.Self as Player); //Needs to run on main thread UnityMainThreadDispatcher.Instance().Enqueue(() => { _gameplaySetupViewController.Setup(false, true, true, false, PlayerSettingsPanelController.PlayerSettingsPanelLayout.Singleplayer); SetLeftScreenViewController(_gameplaySetupViewController, ViewController.AnimationType.In); SetRightScreenViewController(_ongoingGameList, ViewController.AnimationType.In); _ongoingGameList.ClearMatches(); _ongoingGameList.AddMatches(Plugin.client.State.Matches); }); }
void OnLogMessageReceived(object sender, LogMessageReceivedEventArgs args) { UnityMainThreadDispatcher.Instance().Enqueue((() => { //if ((args.MessageType & (LogMessageType.None | LogMessageType.Trace | LogMessageType.Debug | LogMessageType.Info)) != 0) //{ // Debug.Log(args.Message); //} //else if ((args.MessageType & (LogMessageType.Warning)) != 0) { Debug.LogWarning(args.Message); } else if ((args.MessageType & (LogMessageType.Error | LogMessageType.Fatal)) != 0) { Debug.LogError(args.Message); } })); }
void ChannelMemberCountHandler(long requestId, IntPtr channelMember, int channelMemberCount, int errorCode) { Debug.Log(channelMemberCount); int offset = 0; List <ChannelMemberCount> channelMembers = new List <ChannelMemberCount>(); for (var i = 0; i < channelMemberCount; i++) { var ptr = new IntPtr(channelMember.ToInt64() + offset); var cmc = (ChannelMemberCount)Marshal.PtrToStructure(ptr, typeof(ChannelMemberCount)); channelMembers.Add(cmc); Debug.Log(cmc.channelId + ": " + cmc.count); } UnityMainThreadDispatcher.Instance().Enqueue(() => { OnChannelMemberCountReceivedCallback(requestId, channelMembers); }); }
//-------------------------------------------------------------> /// <summary> /// Aplicar una corrección al personaje (local) del jugador si es necesario /// </summary> /// <param name="tick"></param> /// <param name="serverPosition"></param> public void CorrectPlayer(int tick, Vector2 serverPosition) { //Distancia de diferencia entre el jugador local y su representacion en servidor float diffX = bufferPosition[TickToIndex(tick)].x - serverPosition.x; float diffY = bufferPosition[TickToIndex(tick)].y - serverPosition.y; diff = new Vector2(diffX, diffY); //Corregir la posicion if (Mathf.Abs(diffX) > 2 || Mathf.Abs(diffY) > 3) { UnityMainThreadDispatcher.Instance().Enqueue(() => player.transform.position = serverPosition ); } //Enviar info para la interfaz grafica debugInfoScreen.SetDiff(new Vector2(diffX, diffY)); }
private void ReceivedMessage(string v) { if (logging) { Debug.Log($"Received Message: { v}"); } if (v.StartsWith("Pressed")) { v = v.Split('_')[1]; int buttonIndex = 0; int.TryParse(v, out buttonIndex); if (buttonIndex >= 0) { UnityMainThreadDispatcher.Instance().Enqueue(() => ButtonPressed.Invoke(buttonIndex)); } // TEST SendMessageToServer($"Sie haben Knopf {buttonIndex} geklickt!"); } else if (v.StartsWith("pong")) { } else if (v.StartsWith("QR")) { var rgx = new System.Text.RegularExpressions.Regex(@"^[\w]{2}_[\w]{2}_\d{2}_\d{4}$"); var code = v.Substring(3); if (rgx.IsMatch(code)) { SendMessageToServer($"Teilnehmer ID {code} gescannt!"); UnityMainThreadDispatcher.Instance().Enqueue(() => QRCodeEntered.Invoke(code)); } else { SendMessageToServer($"QR Code {v} gescannt! Keine Teilnehmerkennung erkannt!"); } } else { Debug.LogWarning($"RemoteControl received unhandled Message: { v}"); } }
private async void SubmitScoreWhenResolved(string username, ulong userId, LevelCompletionResults results) { var submitScorePkt = new Packet(new SubmitScore { Score = new Score { EventId = Event.EventId, Parameters = _currentParameters, UserId = userId.ToString(CultureInfo.InvariantCulture), Username = username, FullCombo = results.fullCombo, Score_ = results.modifiedScore, Color = "#ffffff" } }); const string backupPath = "backup_score_submission_packets"; // We would like to cache the submit score packet to disk in the event of a score submission failure. // This should be written as binary and ideally also in an HR form. try { if (!Directory.Exists(backupPath)) { Directory.CreateDirectory(backupPath); } System.IO.File.WriteAllBytes(Path.Combine(backupPath, submitScorePkt.Id.ToString() + ".dat"), submitScorePkt.ToBytes()); } catch (Exception ex) { TournamentAssistantShared.Logger.Error(ex.ToString()); } var submitScoreResponse = (await HostScraper.RequestResponse(EventHost, submitScorePkt, typeof(ScoreRequestResponse), username, userId)).SpecificPacket as ScoreRequestResponse; if (submitScoreResponse != null) { var scores = submitScoreResponse.Scores.Take(10).ToArray(); UnityMainThreadDispatcher.Instance().Enqueue(() => SetCustomLeaderboardScores(scores, userId)); } }
public void createUserClicked() { if (createEmail.text.Length == 0 || createPassword.text.Length == 0 || createUsername.text.Length == 0) { MNPopup mNPopup = new MNPopup("Error", "Please Input Correct!"); mNPopup.AddAction("Ok", () => { Debug.Log("Ok action callback"); }); mNPopup.Show(); } else { var user = new ParseUser(); user.Username = createUsername.text; user.Password = createPassword.text; user.Email = createEmail.text; // other fields can be set just like with ParseObject user["nickName"] = createUsername.text; //MNP.ShowPreloader("", "Creating..."); user.SignUpAsync().ContinueWith(t => { MNP.HidePreloader(); if (t.IsFaulted) { // Errors from Parse Cloud and network interactions using (IEnumerator <System.Exception> enumerator = t.Exception.InnerExceptions.GetEnumerator()) { if (enumerator.MoveNext()) { ParseException error = (ParseException)enumerator.Current; // error.Message will contain an error message // error.Code will return "OtherCause" UnityMainThreadDispatcher.Instance().Enqueue(showErrorWithMessage(error.Message)); } } } else { UnityMainThreadDispatcher.Instance().Enqueue(createSuccess()); } }); } }
void SendRequest() { byte[] commandIDBytesToSend = ASCIIEncoding.ASCII.GetBytes(commandID); UnityMainThreadDispatcher.Instance().Enqueue(() => { GUIManager.Instance.videoPlayerPanelController.videoStreamingLogText.text += "Sending request...\n"; }); byte[] frameNoBytesToSend = new byte[FRAME_NO_BYTE_NUM]; Array.Clear(frameNoBytesToSend, 0, frameNoBytesToSend.Length); byte[] frameNoBytes = BitConverter.GetBytes(requestedFrameNo); frameNoBytes.CopyTo(frameNoBytesToSend, 0); //byte[] videoNameBytesToSend = Encoding.UTF8.GetBytes(requestedVideoName); byte[] videoNameBytesToSend = ASCIIEncoding.ASCII.GetBytes(requestedVideoName); NetworkStream serverStream = client.GetStream(); bool requestSent = false; (new Thread(() => { serverStream.Write(commandIDBytesToSend, 0, commandIDBytesToSend.Length); serverStream.Write(frameNoBytesToSend, 0, frameNoBytesToSend.Length); serverStream.Write(videoNameBytesToSend, 0, videoNameBytesToSend.Length); requestSent = true; requestingBeginTime = DateTime.Now; })).Start(); while (!requestSent) { System.Threading.Thread.Sleep(1); } UnityMainThreadDispatcher.Instance().Enqueue(() => { GUIManager.Instance.videoPlayerPanelController.videoStreamingLogText.text += "Request sent!\n"; }); }