我是 Unity 新手,我不知道如何在 Unity 中创建 callBack 函数
。
现在我正在做的是进行查询以从 parse.com
获取数据。数据获取正确,但在同一函数中,当我设置禁用/启用任何 gameobject
时,我收到主线程错误。确切的错误消息是:-
错误-
SetActive can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
我用来获取数据的以下代码/函数。
public void GetTop10ScoreClassic()
{
List<string> fbscores=new List<string>();
List<string> fbplayer=new List<string>();
int i = 0;
int rank = 0;
// Debug.Log (PlayerPrefs.GetString ("FBUserId"));
Debug.Log ("Classic top 10 1");
var query = ParseObject.GetQuery ("ClassicFacebookScore").OrderByDescending("score").Limit(10).WhereContainedIn("userId",FBLogin.friendIDsFromFB);
query.FindAsync().ContinueWith(t =>
{
Debug.Log ("Classic top 10 2");
comments = t.Result;
Debug.Log(t.Result);
foreach (var obj in comments) {
i++;
int score = obj.Get<int>("score");
Debug.Log(score);
string playerName = obj.Get<string>("playerName");
Debug.Log(playerName);
string playerId=obj.Get<string>("userId");
Debug.Log(playerId);
fbscores.Add(score.ToString());
fbplayer.Add(playerName);
if(playerId==userId)
{
rank=i;// to highlight the user's score
}
}
//enable the colliders
foreach (BoxCollider2D colliders in Userrankscore.instance.myColliders)
colliders.enabled = true;
FbLeaderboard.instance.NetworkError = false;
scoreapp42.instance.loadingwindow.SetActive (false);
//Pass the list of score;
App42Score.instance.list (fbscores,fbplayer,"fb",Convert.ToInt32(rank));
if(t.IsFaulted)
{
//enable the colliders
foreach (BoxCollider2D colliders in Userrankscore.instance.myColliders)
colliders.enabled = true;
if(FbLeaderboard.instance.NetworkError)
{
scoreapp42.instance.errorwindow.SetActive(true);
scoreapp42.instance.loadingwindow.SetActive (false);
Debug.LogError("Network Error");
}
foreach(var e in t.Exception.InnerExceptions) {
ParseException parseException = (ParseException) e;
Debug.Log("Error message " + parseException.Message);
Debug.Log("Error code: " + parseException.Code);
}
}
});
}
最佳答案
您不能从另一个线程调用统一函数。因此,如果您希望函数在主线程上运行,请执行以下步骤:
1.在场景中创建一个游戏对象并添加以下脚本:
公共(public)类DoOnMainThread:MonoBehaviour {
public readonly static Queue<Action> ExecuteOnMainThread = new Queue<Action>();
public virtual void Update()
{
// dispatch stuff on main thread
while (ExecuteOnMainThread.Count > 0)
{
ExecuteOnMainThread.Dequeue().Invoke();
}
}
}
2) 每当你想像这样调用它时,将你的协程操作添加到队列中:
DoOnMainThread.ExecuteOnMainThread.Enqueue(() => { StartCoroutine(WaitAlertView4()); } );
它将在主线程下次有机会执行时执行,或者更确切地说,当游戏对象调用其更新方法时执行
关于c# - Parse.com - 如何统一制作回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31758673/