【发布时间】:2021-02-21 20:33:03
【问题描述】:
我正在使用 Unity 和外部引擎(用 c# 编写的可执行文件)编写国际象棋 UI。我可以向流程(引擎)发送和接收数据。这是可行的,但是当调用 Make_Move 方法时,当进程返回数据时,就会出现问题。虽然调试代码执行只是在尝试访问 Make_Move 方法中的 Unity 对象时停止,并且缺少对象,即部分 gameObject 和 sprite,但其余变量(不是统一对象)仍然存在。我没有收到任何错误,所有变量都是一个类的一部分,该类保存在一个数组中,该数组跟踪它的精灵游戏对象以及其他东西。
为什么只有统一对象会从对象数组中消失?
为什么在尝试访问统一对象(精灵等)时代码执行停止?
如何解决这个问题?
用于发送和接收 4 位字符串的 Unity 类,移动的开始和结束位置 (xyxy)
public static class UCI
{
static Process process = new Process();
static UCI()
{
ProcessStartInfo si = new ProcessStartInfo()
{
FileName = "ChessEngine.exe",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true
};
process.StartInfo = si;
process.OutputDataReceived += new DataReceivedEventHandler(OnRecieved);
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
}
public static void SendLine(string command)
{
Debug.Log("send: "+ command);
process.StandardInput.WriteLine(command);
process.StandardInput.Flush();
}
public static void Kill()
{
process.Kill();
}
private static void OnRecieved(object sender, DataReceivedEventArgs e)
{
string text = e.Data;
Debug.Log("Recieved: " + text);
if(text.Length == 4)
Game.Make_Move(new Move(Board.Squares[(int)char.GetNumericValue(text[0]),(int)char.GetNumericValue(text[1])],Board.Squares[(int)char.GetNumericValue(text[2]), (int)char.GetNumericValue(text[3])]));
}
}
出现问题的Unity make_Move方法:
static void Make_Move(Move move)
{
var end = move.end.GetPiece();
//posistion is a vector2Int, this line does not cause any trouble
print("Pos: " + Squares[move.start.GetPosition().x, move.start.GetPosition().y].GetPosition());
//this line causes execution to stop without error. if it is commented out execution will continue.
print("obj: " + Squares[move.start.GetPosition().x, move.start.GetPosition().y].gameObject);
//lines below this is not executed
SetPiece(move.start.gameObject.GetComponent<Image>().sprite, move.end.GetPosition(), end.MoveCnt);
RemovePiece(move.start.GetPosition());
// set the current turn to the other player
CurrentPlayer = CurrentPlayer == players[0] ? CurrentPlayer = players[1] : CurrentPlayer = players[0];
}
【问题讨论】: