我有一点问题。我想,在团结从服务器获得所有信息之后,团结会产生一个预制件。问题是,统一说,实例化函数只能从主线程调用。你有什么想法我可以解决这个问题吗?
public void Init()
{
Debug.Log("Starting Connection.");
Client = new UdpClient(ClientPort);
Client.Connect(IP, ServerPort);
Task.Run(async () =>
{
while (true)
{
var receivedResults = await Client.ReceiveAsync();
string returnData = Encoding.ASCII.GetString(receivedResults.Buffer);
string[] splittedData = returnData.Split('|');
if (splittedData[0] == "POSITION")
{
if (splittedData[1] != PlayerScript.PlayerName)
{
foreach (Player p in Environment.Players)
{
if (p.PlayerName == splittedData[1])
{
p.Position = new Vector3(float.Parse(splittedData[2], System.Globalization.CultureInfo.InvariantCulture), float.Parse(splittedData[3], System.Globalization.CultureInfo.InvariantCulture), float.Parse(splittedData[4], System.Globalization.CultureInfo.InvariantCulture));
p.Rotation = new Vector3(float.Parse(splittedData[5], System.Globalization.CultureInfo.InvariantCulture), float.Parse(splittedData[6], System.Globalization.CultureInfo.InvariantCulture), float.Parse(splittedData[7], System.Globalization.CultureInfo.InvariantCulture));
}
}
}
}
else if (splittedData[0] == "NEWPLAYER")
{
Player User = new Player
{
PlayerName = splittedData[1],
PlayerModel = 0,
Position = new Vector3(float.Parse(splittedData[2], System.Globalization.CultureInfo.InvariantCulture), float.Parse(splittedData[3], System.Globalization.CultureInfo.InvariantCulture), float.Parse(splittedData[4], System.Globalization.CultureInfo.InvariantCulture)),
Rotation = new Vector3(float.Parse(splittedData[5], System.Globalization.CultureInfo.InvariantCulture), float.Parse(splittedData[6], System.Globalization.CultureInfo.InvariantCulture), float.Parse(splittedData[7], System.Globalization.CultureInfo.InvariantCulture))
};
Environment.Players.Add(User);
SpawnNewPlayer(User);
Debug.Log("Player Count: " + Environment.Players.Count);
}
}
});
}
void SpawnNewPlayer(Player user)
{
Instantiate(PlayerModel, user.Position, Quaternion.Euler(user.Rotation));
}