String won't send through socket communication between Unity and MATLAB - c#

I have the following lines of code. I am trying to set "MouseLook.hit" to either the gameObject.name or to "no" if the raycast does not hit. The if statement works, such that the MouseLook.hit prints in Unity. However, I can never receive the object on the other side (it is received in MATLAB). BUT, the "no" in the else statement is received in MATLAB. ALSO, I sometimes receive the message for some of the objects that I have in my Unity environment, but not for the specific ones I want (I have tried swithching to either mesh or box colider). Can you see something wrong with the code? Thank you!
ray = new Ray(transform.position, transform.forward);
if (Physics.Raycast(ray, out raycastHit))
{
MouseLook.hit = raycastHit.collider.gameObject.name;
print(MouseLook.hit);
}
else
{
MouseLook.hit = "no";
}
Byte[] sendBytes5 = Encoding.UTF8.GetBytes(MouseLook.hit);
mySocket1.GetStream().Write(sendBytes5, 0, sendBytes5.Length);
Byte[] sendBytes6 = Encoding.UTF8.GetBytes(" ");
mySocket1.GetStream().Write(sendBytes6, 0, sendBytes6.Length);
I tried to change the encoding, I tried to change the objects in the hierarchy, I tried to change the if and else if statement, I tried to change to meshcolider to boc colider for the objects I am aiming at in the game.

Related

Unity google play games realtime message not send

So i'm currently working on a game with unity, it's an air hockey. And i would like to add a multiplayer mode (1 vs 1).
So after the player have a match with an opponent, they are connected in a room where the game begins.
But i'm having issue when i want to receive the opponent message.
In the player script movement, i add this on the void update()
Multiplayer.Instance.SendMyUpdate(positionX, PositionZ);
and in the multiplayer script, i add this:
public void SendMyUpdate(float posX, float posZ) {
string PlayerUserNameString = PlayGamesPlatform.Instance.RealTime.GetSelf ().DisplayName;
char[] characters = PlayerUserNameString.ToCharArray ();
string data = characters + ":" + posX + ":" + posZ;
byte[] bytedata = System.Text.ASCIIEncoding.Default.GetBytes (data);
PlayGamesPlatform.Instance.RealTime.SendMessageToAll (false, bytedata);
}
And on the method OnRealTimeMessageReceived:
string rawdata = System.Text.ASCIIEncoding.Default.GetString (data);
string[] cut = rawdata.Split (new string[] { ":" }, System.StringSplitOptions.RemoveEmptyEntries);
OpponentUserName = System.Convert.ToSingle (cut[1]).ToString();
Transform target = GameObject.Find ("mallet Opponent").transform;
Vector3 newpos = new Vector3
(
System.Convert.ToSingle(cut[2]),
0,
System.Convert.ToSingle(cut[3])
);
After i wrote this and build it on two devices, when the room is connected and the game begins, the opponent player doesn't move at all, and i don't know where the issue.
Any ideas?
Arrays are zero based so opponent user name should be cut[0] and:
System.Convert.ToSingle(cut[3])
cut[3] will look for the 4th split result and there are only three so an exception will occur. That is enough to prevent the method working and the position updating. If so there should also be an error in the console log.
However perhaps the OnRealTimeMessageReceived is not even being called. You need to throw in some breakpoints and debug, or add some debug logs to see how far things are getting. If it isn't even getting to a method you expect then the question can be rephrased "why is method X not being called"

Unity GameObject with list containing other objects

For a school project i'm working with Unity. Im making a "game" where you need to connect devices with cables.
So I have a object called "device" with a script "deviceController". The Device object has a List containing other objects with a script called "portController".
Currently im trying to set a bool(anyCablesConnected) to true in the deviceController, if there are any cables in a port to a device and if there are no cables connected to the device set the bool to false. The portController also has a bool called "Occupied".
Only I have no idea how to do this. Do I use a foreach loop or something like that ?
foreach(port in device){
// IF A PORT FROM A DEVICE IS OCCUPIED, SET ANYCABLESCONNECTED TO TRUE
if (occupied == true){
anyCablesConnected = true;
} else {
anyCablesConnected = false;
}
}
Something like this ? I haven't really worked with foreach loops. But I hope you guys can help me !
If I understand you correctly, anyCablesConnected should be true iff at least one cable is connected. The logic for that is:
anyCablesConnected = false;
foreach (var port in device)
{
// IF A PORT FROM A DEVICE IS OCCUPIED, SET ANYCABLESCONNECTED TO TRUE
if (port.GetComponent<portController>().occupied)
{
anyCablesConnected = true;
// No need to continue looping, we have already found a cable
break;
}
}
Or you can use LINQ for a more compact solution:
anyCablesConnected = device.Any(x => x.GetComponent<portController>().occupied);
Note that I have made some assumptions as to how your occupied flag is accessed!
Alright, while writing the answer seems to have popped up. But to spare me deleting everything while giving you some context on how foreach works.
A list containing strings; List<string>, would be written like this:
List<string> listWithStrings = new List<string>();
listWithStrings.Add("Hello");
listWithStrings.Add("World");
and looped through with a foreach:
foreach (string stringInList in listWithStrings) {
Debug.Log(stringInList);
// The first loop stringInList will be "Hello",
// the second loop it will be "World"
}
Which is pretty much the same as a standard for-loop would be:
for (int i = 0; i < listWithStrings.Count; i++) {
Debug.Log(listWithStrings[i]);
}
But a lot easier and cleaner.

BASS WASAPI BPMCounter

I want to analyse my default playback device and detect the beats. I've been using the BASS WASAPI to get the FFT data of the selected device with:
int ret = BassWasapi.BASS_WASAPI_GetData(_fft, (int)BASSData.BASS_DATA_FFT2048);
Now I was using the data to generate spectrum data and display this to the user. In addition I want to detect the Beats using the BPMCounter Class from BASS. However as far as I can tell the BPMCounter.ProcessAudio() function requires a stream (which I don't get with WASAPI) in order to work. Is there a ways I can use BPMCounter with WASAPI? Would be great if someone can point me to the right direction. Thanks
Edit:
Tried this to convert the data to a stream, but without success:
int ret = BassWasapi.BASS_WASAPI_GetData(_fft, (int)BASSData.BASS_DATA_FFT2048); //get channel fft data
var chan = Bass.BASS_StreamCreate(0, 44100, BASSFlag.BASS_DEFAULT, BASSStreamProc.STREAMPROC_PUSH);
Bass.BASS_ChannelPlay(chan, false);
Bass.BASS_StreamPutData(chan, _fft, _fft.Length);
bool beat = _count.ProcessAudio(chan, true);
Debug.Write(beat);
beat is always False, however I can see at the Spectrum that the capturing of the FFT Data is corrent.
I've just started playing with this lib a few hours ago and i am still going through the examples. So my answer maybe is not what you want. For my project i also want to transform WASAPI into a stream and use it for a displaying a spectrum. What i did was to create a StreamPush, right after BASS_WASAPI initialization.
To init your WASAPI use this call and this delegate:
private InitWasapi()
{
WASAPIPROC _process = new WASAPIPROC(Process); // Delegate
bool res = BassWasapi.BASS_WASAPI_Init(_YourDeviceNumber, 0, 0, BASSWASAPIInit.BASS_WASAPI_BUFFER, 1f, 0f, _process, IntPtr.Zero);
if (!res)
{
// Do error checking
}
// This is the part you are looking for (maybe!)
// Use these flags because Wasapi needs 32-bit sample data
var info = BassWasapi.BASS_WASAPI_GetInfo();
_stream = Bass.BASS_StreamCreatePush(info.freq, info.chans, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_FLOAT, IntPtr.Zero);
BassWasapi.BASS_WASAPI_Start();
}
private int Process(IntPtr buffer, int length, IntPtr user)
{
Bass.BASS_StreamPutData(_stream, buffer, length);
return length;
}
Please note: This works, but i am still experimenting. For example i am not getting the same spectrum output as when i create the stream from the music file itself. There are some (small) differences. Maybe it's because i am using a custom EQ in Winamp for playing the same .mp3. So if anyone knows more on this subject, i would like also to hear it!

unity freezes due to use of system.IO.ports.serialport

I am using a c# script to send things over serial. Everything works out fine. The other end is getting all the right data. Problem is, it only works for about 110 to 30 seconds, then unity freezes. I know that this is better suited for the unity forums, but i dont seem to get any replies there, so i have come here.
code below:
using UnityEngine;
using System.Collections;
using System.IO.Ports;
public class NewBehaviourScript : MonoBehaviour {
byte[] StepperAngle = new byte[1];
short servoAngle = 0;
byte[] servoArray = new byte[2];
SerialPort sp = new SerialPort("COM4", 9600);
// Use this for initialization
void Start () {
sp.Open();
sp.ReadTimeout = 1;
}
// Update is called once per frame
void Update () {
StepperAngle[0] = (byte)(transform.localEulerAngles.y * 50/360);
servoAngle = (short)(transform.localEulerAngles.z* 10e8); // turn fl2oat into short. short is split right down center
servoArray[0] = (byte)(servoAngle/10e8);
servoArray[1] = (byte)(servoAngle % 10e8);
sp.Write(StepperAngle,0,1);
//try{
//print(StepperAngle[0]);
//}catch(System.Exception){
//print("stupid " + stepperAngle);
//}
}
}
and also, the culprit IS the line sp.Write(StepperAngle[0]); When commented out everything goes fine.
Yaay. It seems that the issue was not in fact the sp.Write(); call but in fact was the input buffer overflowing. It seems that the arduino code was writing and the unity code was not reading. This caused Unity to freeze up. How removing sp.Write(StepperAngle,0,1); fixed it I have no idea.

Write Failure on sending video to youtube flash player

I'm having a problem with a youtube cache I'm trying to make (my internet connection is really slow). It works by detecting if a videoplayback page is requested and saves the response to the disk. It works fine with lightspark and the html5 player on FireFox, but when I try it on Google Chrome I get a Write Failure in RespCacheCallback.
I have the source here as it is too long to be posted with the question.
I forgot to add the range to the ID created in the program when I searched the cache, which meant that the program tried to send the entire video when a small portion was requested, which made the player close the connection. That was fixed by adding this method to MainClass
static bool TryGetRange (string url, out string range)
{
int index = url.IndexOf ("&range=");
if (index == -1) {
range = null;
return false;
}
index += 7;
int len = url.IndexOf ('&',index) - index;
range = url.Substring (index,len);
return true;
}
This method checks if the range parameter is present in the url, and then gets the value of it.
Then adding this code before if(File.Exists (requestData.Signature + "_done"))
string range;
if(TryGetRange (requestString, out range))
{
requestData.Signature += range;
}
This adds the range to the signature if the range parameter is detected

Categories

Resources