【发布时间】:2015-09-16 10:10:07
【问题描述】:
嘿,我正在使用 unity3d 制作安卓游戏,我想从我的笔记本电脑控制我的游戏我制作了一个 TCP/IP 聊天之类的程序,通过互联网从键盘获取输入到我的安卓我为我的笔记本电脑制作了一个(Windows 形式的 APP)和 Unity 的一个,除了一点恼人的错误外,一切正常。
错误: 当我按下 X 按钮时,我想将球体从 A 点移动到 B 点,但是当发送“x”值时,它会显示:
INTERNAL_get_position 只能从主线程调用。 加载场景时,构造函数和字段初始化程序将从加载线程中执行。 不要在构造函数或字段初始化程序中使用此函数,而是将初始化代码移至 Awake 或 Start 函数。
当我关闭 Windows 窗体 APP 时,球会移动,我也尝试了 Awake 和启动功能。
PS:我在同一台计算机上测试它,所以它与 IPAddresses 无关。
这是我的统一部分代码:
using UnityEngine;
using System.Collections;
using System.Text;
using System;
using System.Net;
using System.Net.Sockets;
public class CHAT : MonoBehaviour {
private Socket sck;
EndPoint epLocal, epRemote;
//Gameobjects
public Transform ball , point;
//logic
string xIsHere;
// Use this for initialization
void Start () {
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
epLocal = new IPEndPoint(IPAddress.Parse("192.168.1.9"), Convert.ToInt32("81"));
sck.Bind(epLocal);
epRemote = new IPEndPoint(IPAddress.Parse("192.168.1.9"), Convert.ToInt32("80"));
sck.Connect(epRemote);
Debug.Log("COnnected");
}
void Awake()
{
}
// Update is called once per frame
void Update () {
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCAllBack), buffer);
}
private void MessageCAllBack(IAsyncResult aResult)
{
try
{
int size = sck.EndReceiveFrom(aResult, ref epRemote);
if (size > 0)
{
byte[] receivedData = new byte[1464];
receivedData = (byte[])aResult.AsyncState;
ASCIIEncoding eEncoding = new ASCIIEncoding();
string receivedMessage = eEncoding.GetString(receivedData);
//bn3mal if statement bnshof weslat el X wela la2 w iza weslat bnmasi el tabeh
xIsHere = receivedMessage;
if (xIsHere.Contains("x"))
{
Debug.Log("X is here");
ball.position = Vector3.MoveTowards(ball.position, point.position, 5 * Time.deltaTime);
}
//b3deen bntba3 el msg bs b7aletna bdna n5li el touch active.
//ListMessage.Items.Add("Sender:" + receivedMessage);
}
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCAllBack), buffer);
}
catch(Exception exp)
{
Debug.Log(exp.ToString());
}
}
}
【问题讨论】:
-
问题在于异步回调。
MessageCAllBack将从另一个线程调用,并且由于 Unity 不是线程安全的,任何修改游戏对象的尝试都会导致该错误。也许您应该在某些内容到达后尝试设置一个标志,然后更新您的Update()函数中的位置并再次清除标志?也许你也可以使用协程。