Rewriting Text.text will behave strangely.
I am using the text of the Text component to display the log on the game screen in Unity. Since there is an asynchronous operation that is received by TCP, Log is put in the queue once, and it is retrieved and displayed in Update method.
private void Update()
{
if (LogQueue.Count > 0)
{
var msg = LogQueue.Dequeue();
Debug.Log(msg);
LogText.text = msg + "\n" + LogText.text;
}
}
public void CreateServer()
{
var portText = IpInput.text;
var port = int.Parse(portText);
server = new TcpListener(IPAddress.Any,port);
server.Start();
server.BeginAcceptTcpClient(new AsyncCallback(AcceptClientCallback), server);
LogQueue.Enqueue($"Server listening on port {port}");
LogQueue.Enqueue($"wait client ...");
}
private void AcceptClientCallback(IAsyncResult ar)
{
var listener = (TcpListener)ar.AsyncState;
client = listener.EndAcceptTcpClient(ar);
stream = client.GetStream();
var msg = System.Text.Encoding.ASCII.GetBytes("connected");
stream.Write(msg, 0, msg.Length);
LogQueue.Enqueue("connectd");
var buffer = new byte[128];
stream.BeginRead(buffer, 0, buffer.Length, ReadStreamCallBack, buffer);
}
private void ReadStreamCallBack(IAsyncResult ar)
{
Debug.Log("called");
var buffer = (byte[])ar.AsyncState;
var msg = System.Text.Encoding.ASCII.GetString(buffer, 0, buffer.Length);
LogQueue.Enqueue(msg);
var back = System.Text.Encoding.ASCII.GetBytes("received");
stream.Write(back, 0, back.Length);
var nextBuffer = new byte[128];
stream.BeginRead(nextBuffer, 0, nextBuffer.Length, ReadStreamCallBack, nextBuffer);
}
When actually executed, the log of synchronous processing is displayed correctly as shown below.
sync log 1
sync log 2
sync log 1
sync log 3
sync log 2
sync log 1
However, when the log of a message received asynchronously with TCP starts to be displayed, the previous log disappears and only the latest log is displayed.
received message 1
received message 2
received message 3
Why is this happening?
Remove Null Character or receive only the required length.
Removal:
str = str.TrimEnd ('\ 0');