I have a piece of code that I want to use with Unity 2018.2.14.f1.
#if UNITY_WSA && !UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Devices.SerialCommunication;
namespace SerialForUWP
{
public class SerialComHelper
{
public async static Task<string[]> GetPorts()
{
var serials = SerialDevice.GetDeviceSelector();
var coms = await DeviceInformation.FindAllAsync(serials);
List<string> results = new List<string>();
foreach (var device in coms)
{
using (var serialDevice = await SerialDevice.FromIdAsync(device.Id))
{
if (serialDevice != null)
{
var port = serialDevice.PortName;
results.Add(port.ToString());
}
}
}
return results.ToArray();
}
}
}
#endif
I compile for UWP using IL2CPP :
I also already updated the manifest of the cpp projet :
<DeviceCapability Name="serialcommunication">
<Device Id="any">
<Function Type="name:serialPort" />
</Device>
</DeviceCapability>
As soon as I try to use the GetPorts() function my app freeze.
void Update()
{
text.text = Time.time.ToString();
if (Input.GetKeyUp(KeyCode.Space))
{
try
{
#if UNITY_WSA && !UNITY_EDITOR
foreach (var com in SerialForUWP.SerialComHelper.GetPorts().Result)
{
text.text = com;
}
#endif
}
catch (Exception ex)
{
text.text = ex.ToString();
}
}
}
I got no error, no exception.
Can anyone help please ?
To get the exceptions use:
Debug.Log(ex.ToString()) instead of Text.text = ex.ToString()
According to this answer I can't use .Result
Related
This is the code I am using for QR Scan. It uses XR for Camera input and ZXing to decode the QR Code. I have been at this for 3 days and still have no clue what I am doing wrong. I do not know whether it is that code isn't able to decode the QR, or it can but isn't able to print it out on Output text. Any help would be greatly appreciated. Thank you! :)
These are the libraries I am using :
using System.Collections;
using UnityEngine;
using UnityEngine.XR.ARSubsystems;
using UnityEngine.XR.ARFoundation;
using ZXing;
using TMPro;
This is the code :
IBarcodeReader _reader;
ARCameraManager _arCam;
AudioSource _audioSrc;
ARRaycastManager _arRay;
private Texture2D _arTexture;
private TextMeshPro _outputText;
private void Awake()
{
_arCam = FindObjectOfType<ARCameraManager>();
_audioSrc = FindObjectOfType<AudioSource>();
_arRay = FindObjectOfType<ARRaycastManager>();
_reader = new BarcodeReader();
_arCam.frameReceived += OnCameraFrameReceived; //When camera receives frame.
}
//Fires off when Frame is received.
void OnCameraFrameReceived(ARCameraFrameEventArgs eventArgs)
{
if ((Time.frameCount % 15) == 0)
{
XRCpuImage _image;
if(_arCam.TryAcquireLatestCpuImage(out _image))
{
StartCoroutine(ProcessQRCode(_image));
_image.Dispose();
}
}
}
//Processes the QR Code in the _image.
IEnumerator ProcessQRCode(XRCpuImage _image)
{
var request = _image.ConvertAsync(new XRCpuImage.ConversionParams { inputRect = new RectInt(0, 0, _image.width, _image.height),
outputDimensions = new Vector2Int(_image.width / 2, _image.height / 2),
outputFormat = TextureFormat.RGB24
});
while (!request.status.IsDone())
yield return null;
if (request.status != XRCpuImage.AsyncConversionStatus.Ready)
{
Debug.LogErrorFormat("Request failed with status {0}", request.status);
request.Dispose();
yield break;
}
var rawData = request.GetData<byte>();
if(_arTexture == null)
{
_arTexture = new Texture2D(
request.conversionParams.outputDimensions.x,
request.conversionParams.outputDimensions.y,
request.conversionParams.outputFormat,
false
);
}
_arTexture.LoadRawTextureData(rawData);
_arTexture.Apply();
byte[] barcodeBitmap = _arTexture.GetRawTextureData();
LuminanceSource source = new RGBLuminanceSource(barcodeBitmap, _arTexture.width, _arTexture.height);
var result = _reader.Decode(source);
if(result != null)
{
var QRContents = result.Text;
_outputText.text = QRContents;
_audioSrc.Play();
}
}
I am making online multiplayer game with Darkrift2 and with Unity.
I deeply know how to make games but i am new at online part.
I made the game succesfully with LAN.
I done the server side.
But just the game that opened with server can connect.
I am putting the server to my pc and go and open the game in another pc.
It can't connect.
I could definitely make an obvious mistake but IPV4 ADDRESS IS SAME AS PC'S IPV4 ADDRESS AND PORT NO IS SAME ON EVERY PC.
Also there is no firewall ban, Game is opening in another pc's.
By the way probably you don't have to read the whole code, Just the connection part.
Client
NetworkManager.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DarkRift.Client.Unity;
using DarkRift;
using Tags;
using DarkRift.Client;
using UnityEngine.InputSystem;
using System.Net;
using System.Linq;
public class NetworkManager : MonoBehaviour
{
IPAddress IPv4;
public UnityClient client;
public GameObject Bug;
public Transform[] PlayerBegin;
public Light DirLight;
public List<GameObject> Bugs;
private void Awake()
{
IPv4 = Dns.GetHostEntry(Dns.GetHostName())
.AddressList.First(
f => f.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
Debug.Log(IPv4);
client.Connect(IPv4, client.Port, true);
client.MessageReceived += OnMessageReceived;
//DontDestroyOnLoad(gameObject);
}
private void OnDestroy()
{
client.MessageReceived -= OnMessageReceived;
}
public void Interaction(byte Condition)//legdeathi de içine koyunca sorun yaratır mı? sanırım hayır
{
using (DarkRiftWriter writer = DarkRiftWriter.Create())
{
writer.Write(client.ID);
writer.Write(Condition);
using (Message message = Message.Create((ushort)Models.Tags0.InteractionType, writer))
{
client.SendMessage(message, SendMode.Reliable);
}
}
}
public void PosRot(Vector3 Pos, Quaternion Rot, bool ThereIsPos)
{
XYZ Position=null;
if (ThereIsPos)
{
Position = new XYZ();
Position.X = Pos.x;
Position.Y = Pos.y;
Position.Z = Pos.z;
}
XYZ Rotation = new XYZ();
Rotation.X = Rot.x;
Rotation.Y = Rot.y;
Rotation.Z = Rot.z;
float RotW = Rot.w;
using (DarkRiftWriter writer = DarkRiftWriter.Create())
{
writer.Write(client.ID);
var tag = Models.Tags0.Rot;
if (ThereIsPos)
{
tag = Models.Tags0.PosRot;
writer.Write(Position);
}
writer.Write(Rotation);
writer.Write(RotW);
using (Message message = Message.Create((ushort)tag, writer))
{
client.SendMessage(message, SendMode.Unreliable);
}
}
}
public int PlayerId;
public ushort PlayerCount;
private void OnMessageReceived(object sender, MessageReceivedEventArgs e)
{
using (Message message = e.GetMessage())
{
using (DarkRiftReader reader = message.GetReader())
{
if (message.Tag == (ushort)Models.Tags0.InteractionType)
{
ushort Id = reader.ReadUInt16();
GameObject tarantula = Bugs[Id].transform.GetChild(0).gameObject;
byte Interaction = reader.ReadByte();
Spider s = tarantula.GetComponent<Spider>();
switch (Interaction)
{
case 0: s.Attack(); break;
case 1:
s.DefenceGetBug();
break;
case 2:
s.DefenceOff();
break;
case 3:
s.Death();
break;
case 4:
s.LegsHealthDown();
break;
default:
s.LegHealthDown(s.Legs[Interaction - 5], 3);
break;
}
}
byte ThereIsPos=0;
if(message.Tag == (ushort)Models.Tags0.PosRot)
{
ThereIsPos = 1;
}
else if(message.Tag == (ushort)Models.Tags0.Rot)
{
ThereIsPos = 2;
}
if (ThereIsPos != 0)
{
ushort Id = reader.ReadUInt16();
GameObject tarantula = Bugs[Id].transform.GetChild(0).gameObject;
if (ThereIsPos == 1)
{
XYZ Position = reader.ReadSerializable<XYZ>();
tarantula.transform.position = new Vector3(Position.X, Position.Y, Position.Z);
}
XYZ Rotation = reader.ReadSerializable<XYZ>();
float RotW = reader.ReadSingle();
tarantula.transform.rotation = new Quaternion(Rotation.X, Rotation.Y, Rotation.Z, RotW);
}
if (message.Tag == (ushort)Models.Tags0.NewPlayer)
{
PlayerCount = (ushort)(reader.ReadUInt16() + 1);
//Debug.Log("PlayerCount : " + PlayerCount);
PlayerId = Bugs.Count;//Player No
//Debug.Log("PlayerId : " + PlayerId);
while (PlayerId < PlayerCount)
{
Debug.Log("Player Spawn" + PlayerId);
GameObject bug = Instantiate(Bug, PlayerBegin[PlayerId].position, Quaternion.identity, null);
bug.name = "Bug" + PlayerId;
Spider spider;
spider = bug.GetComponentInChildren<Spider>();
spider.nm = this;
spider.DirLight = DirLight;
//spider.transform.position = PlayerBegin[PlayerId].position;
//PosChange(spider.gameObject.transform.position);
if (client.ID != PlayerId)
{
//spider.enabled = false;
bug.transform.Find("Camera").gameObject.SetActive(false);
bug.transform.Find("CM FreeLook1").gameObject.SetActive(false);
bug.transform.Find("Camera Late").gameObject.SetActive(false);
bug.transform.Find("Canvas").gameObject.SetActive(false);
bug.GetComponentInChildren<PlayerInput>().enabled = false;
}
Bugs.Add(bug);
PlayerId++;
}
}
}
}
}
}
Server code .Net (only the main class):
using System;
using DarkRift.Server;
using DarkRift;
using Tags;
namespace Bug_Wars_Online
{
public class BugWarsOnline : Plugin
{
public override bool ThreadSafe => false;
public override Version Version => new Version(1, 0, 0);
public BugWarsOnline(PluginLoadData pluginLoadData) : base(pluginLoadData)
{
ClientManager.ClientConnected += OnClientConnected;
ClientManager.ClientDisconnected += OnClientDisconnected;
}
private void OnClientConnected(object sender, ClientConnectedEventArgs e)
{
Console.WriteLine("Connected");
e.Client.MessageReceived += OnMessageReceived;
using (DarkRiftWriter writer = DarkRiftWriter.Create())
{
writer.Write(e.Client.ID);
writer.Write(0);
using (Message message = Message.Create((ushort)Models.Tags0.NewPlayer, writer))
{
foreach (IClient client in ClientManager.GetAllClients())
{
//if (client.ID != e.Client.ID)
{
client.SendMessage(message, SendMode.Reliable);
Console.WriteLine("Player" + client.ID + " Connected");
Console.WriteLine("ClientManager.Count" + ClientManager.Count);
}
}
}
}
}
private void OnClientDisconnected(object sender, ClientDisconnectedEventArgs e)
{
Console.WriteLine("Disconnected");
//destroy et!
}
private void OnMessageReceived(object sender, MessageReceivedEventArgs e)
{
using (Message message = e.GetMessage())
{
if (message.Tag == (ushort)Models.Tags0.PosRot|| message.Tag == (ushort)Models.Tags0.Rot)
{
foreach (IClient client in ClientManager.GetAllClients())
{
if (client.ID != e.Client.ID)
{
client.SendMessage(message, SendMode.Unreliable);
}
}
}
if (message.Tag == (ushort)Models.Tags0.InteractionType)
{
foreach (IClient client in ClientManager.GetAllClients())
{
if (client.ID != e.Client.ID)
{
client.SendMessage(message, SendMode.Reliable);
}
}
}
}
}
}
}
Okay I should have enter the ipv4 address of server’s pc.
I am working on an application for the HoloLens (1) based on Unity. I am trying to send data via TCP from a Qt-based application (Windows) to the HoloLens. Wireshark shows, that my test package is correctly sent and acknowledged by the HoloLens. The data starts with four bytes containing the length of the message, which starts right after those four bytes. In the following code, first, the four bytes are trying to be received, and afterwards, the message itself.
After executing the code for connecting and sending the data in the client application, StreamSocketListener_ConnectionReceived() is called on the HoloLens. In the next Update() call, ReadTcpData() is called. Now, execution 'stops' at the first call to
tcpMessageSizeBuffer[tcpMessageSizeBytesRead++] = (byte)stream.ReadByte();
At least the debugger jumps out of the code when I try to step over the line. There is no exception caught in the catch block.
I was expecting that the EndOfStream property of StreamReader would be false if there is nothing to read, and consequently, I would receive a valid byte from the stream when calling ReadByte when it was true. I have no clue what goes wrong here. Any hints would be greatly appreciated.
using System;
using System.IO;
using UnityEngine;
#if UNITY_WINRT && !UNITY_EDITOR
using Windows.Networking.Sockets;
using Windows.Networking;
using Windows.Networking.Connectivity;
using Windows.Storage.Streams;
using System.Runtime.InteropServices.WindowsRuntime;
#endif
public class NetworkManager : MonoBehaviour
{
public int tcpPort;
#if UNITY_WINRT && !UNITY_EDITOR
private StreamSocketListener streamSocketListener;
private StreamReader tcpStreamReader = null;
private StreamSocketListenerConnectionReceivedEventArgs connectionArgs;
private DatagramSocket datagramSocket;
private MemoryStream pendingDatagramSocketStream;
#endif
private UInt32 tcpMessageSizeByteCount;
private UInt32 tcpMessageSizeBytesRead;
private byte[] tcpMessageSizeBuffer;
private bool tcpMessageSizeReceived;
private UInt32 tcpMessageByteCount;
private UInt32 tcpMessageBytesRead;
private byte[] tcpMessageBuffer;
// Use this for initialization
void Start()
{
Application.runInBackground = true;
ResetTcpConnection();
}
public void ResetTcpConnection()
{
#if UNITY_WINRT && !UNITY_EDITOR
ResetTcpRead();
if (streamSocketListener != null)
{
tcpStreamReader.Dispose();
tcpStreamReader = null;
connectionArgs = null;
streamSocketListener.Dispose();
streamSocketListener = null;
}
streamSocketListener = new StreamSocketListener();
streamSocketListener.ConnectionReceived += this.StreamSocketListener_ConnectionReceived;
streamSocketListener.BindServiceNameAsync(tcpPort.ToString());
#endif
}
#if UNITY_WINRT && !UNITY_EDITOR
// Process the client connection.
private async void StreamSocketListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
connectionArgs = args; // Keep this alive
tcpStreamReader = new StreamReader(connectionArgs.Socket.InputStream.AsStreamForRead());
}
#endif
// Update is called once per frame
void Update()
{
#if UNITY_WINRT && !UNITY_EDITOR
if (tcpStreamReader != null && !tcpStreamReader.EndOfStream)
{
Stream stream = tcpStreamReader.BaseStream;
ReadTcpData(ref stream);
}
#endif
}
private void ResetTcpRead()
{
tcpMessageSizeByteCount = sizeof(UInt32);
tcpMessageSizeBytesRead = 0;
tcpMessageSizeBuffer = new byte[tcpMessageSizeByteCount];
tcpMessageSizeReceived = false;
tcpMessageByteCount = 0;
tcpMessageBytesRead = 0;
tcpMessageBuffer = null;
}
private void ReadTcpData(ref Stream stream)
{
try
{
if (!tcpMessageSizeReceived)
{
#if UNITY_WINRT && !UNITY_EDITOR
while(tcpMessageSizeBytesRead < tcpMessageSizeByteCount && !tcpStreamReader.EndOfStream)
{
tcpMessageSizeBuffer[tcpMessageSizeBytesRead++] = (byte)stream.ReadByte();
}
if(tcpMessageSizeBytesRead == tcpMessageSizeByteCount)
{
tcpMessageByteCount = BitConverter.ToUInt32(tcpMessageSizeBuffer, 0);
}
#endif
if (tcpMessageByteCount > 0)
{
tcpMessageBuffer = new byte[tcpMessageByteCount];
tcpMessageSizeReceived = true;
}
}
else
{
// Read the message
int bytesToRead = (int)(tcpMessageByteCount - tcpMessageBytesRead);
bytesToRead = bytesToRead > 10000 ? 10000 : bytesToRead;
int bytesRead = stream.Read(tcpMessageBuffer, (int)tcpMessageBytesRead, bytesToRead);
tcpMessageBytesRead += (uint)bytesRead;
// Did we finish reading the message?
if (tcpMessageBytesRead >= tcpMessageByteCount)
{
ResetTcpRead();
}
}
}
catch (Exception e)
{
throw e;
}
}
}
Found the problem - I have to use BinaryReader and replace the code reading the length of the message such:
while(tcpMessageSizeBytesRead < tcpMessageSizeByteCount)
{
tcpMessageSizeBuffer[tcpMessageSizeBytesRead++] = (byte)binaryReader.ReadByte();
}
For the sake of consistency, also the part of the code actually reading the message can be adapted to use BinaryReader.
I am developing a QR code decoder for my project.
I took the reference from Unity Zxing QR code scanner integration
I am using unity 2018+ and Vuforia 7+
Can Anyone help me where I have made a mistake?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Vuforia;
using ZXing;
using System;
[AddComponentMenu("System/QRScanner")]
public class QRScanner : MonoBehaviour
{
private bool cameraInitialized;
private BarcodeReader barCodeReader;
void Start()
{
barCodeReader = new BarcodeReader();
StartCoroutine(InitializeCamera());
}
private IEnumerator InitializeCamera()
{
// Waiting a little seem to avoid the Vuforia's crashes.
yield return new WaitForSeconds(1.25f);
var isFrameFormatSet = CameraDevice.Instance.SetFrameFormat(Image.PIXEL_FORMAT.GRAYSCALE, true);
Debug.Log(String.Format("FormatSet : {0}", isFrameFormatSet));
// Force autofocus.
var isAutoFocus = CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO);
if (!isAutoFocus)
{
CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_NORMAL);
}
Debug.Log(String.Format("AutoFocus : {0}", isAutoFocus));
cameraInitialized = true;
}
private void Update()
{
if (cameraInitialized)
{
try
{
var cameraFeed = CameraDevice.Instance.GetCameraImage(Image.PIXEL_FORMAT.GRAYSCALE);
if (cameraFeed == null)
{
return;
}
var data = barCodeReader.Decode(cameraFeed.Pixels, cameraFeed.BufferWidth, cameraFeed.BufferHeight, RGBLuminanceSource.BitmapFormat.RGB24);
if (data != null)
{
// QRCode detected.
Debug.Log("Detected");
Debug.Log(data.Text);
}
else
{
Debug.Log("No QR code detected !");
}
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
}
}
}
Result right now: "QR code not detected".
Target which I am using working on other qr code reader app
I notice that Parse Unity support still doesn't provide push notification for iOS.
Has anyone implemented a Unity plugin or another solution to support iOS Push Notifications via Parse?
(Cross posted on Unity Answers.)
It's actually possible now, using a ParseObject to mock up the ParseInstallation object.
Gist here: https://gist.github.com/gfosco/a3d092651c32ba3385e6
Explanation in the Parse Google Group: https://groups.google.com/d/msg/parse-developers/ku8-r91_o6s/6ioQ9T2TP7wJ
Attach this script to a GameObject, replace the important parts with your own:
using UnityEngine;
using System.Collections;
using Parse;
public class PushBehaviorScript : MonoBehaviour {
bool tokenSent = false;
public ParseObject currentInstallation = null;
void Start () {
if (PlayerPrefs.HasKey ("currentInstallation")) {
string objId = PlayerPrefs.GetString ("currentInstallation");
currentInstallation = ParseObject.CreateWithoutData ("_Installation", objId);
}
if (currentInstallation == null) {
#if UNITY_IPHONE && !UNITY_EDITOR
NotificationServices.RegisterForRemoteNotificationTypes (RemoteNotificationType.Alert | RemoteNotificationType.Badge | RemoteNotificationType.Sound);
#endif
}
}
void FixedUpdate () {
if (!tokenSent && currentInstallation == null) {
#if UNITY_IPHONE && !UNITY_EDITOR
byte[] token = NotificationServices.deviceToken;
if(token != null) {
tokenSent = true;
string tokenString = System.BitConverter.ToString(token).Replace("-", "").ToLower();
Debug.Log ("OnTokenReived");
Debug.Log (tokenString);
ParseObject obj = new ParseObject("_Installation");
obj["deviceToken"] = tokenString;
obj["appIdentifier"] = "com.parse.unitypush";
obj["deviceType"] = "ios";
obj["timeZone"] = "UTC";
obj["appName"] = "UnityPushTest";
obj["appVersion"] = "1.0.0";
obj["parseVersion"] = "1.3.0";
obj.SaveAsync().ContinueWith(t =>
{
if (obj.ObjectId != null) {
PlayerPrefs.SetString ("currentInstallation", obj.ObjectId);
}
});
}
#endif
}
}
}
To implement iOS push with parse.com You need to get the token from apple first. Then save Current instalation
Unity does have this functionality build in now.
//push notification
bool tokenSent = false;
void RegisterForPush()
{
Debug.Log("Register for push");
tokenSent = false;
#if UNITY_IOS
UnityEngine.iOS.NotificationServices.RegisterForNotifications(NotificationType.Alert |
NotificationType.Badge |
NotificationType.Sound, true);
#endif
}
void Update () {
if (!tokenSent) {
byte[] token = UnityEngine.iOS.NotificationServices.deviceToken;
if (token != null) {
// send token to a provider
tokenSent = true;
string hexToken = "%" + System.BitConverter.ToString(token).Replace('-', '%');
#if UNITY_IOS
ParseManager.instance.RegisterForPush(hexToken);
#endif
}
}
}
And inside ParseManager (or whatever class you use to manage parse>client communication)
public void RegisterForPush(string token) {
Debug.Log("Parse updating instalation");
ParseInstallation instalation = ParseInstallation.CurrentInstallation;
instalation["deviceToken"] = token;
instalation["user"] = ParseUser.CurrentUser.ObjectId;
instalation["timeZoneOffset"] = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
instalation.SaveAsync();
}
Tested on Unity 5.1.2 and iOS 8.4