【发布时间】:2017-05-21 23:55:20
【问题描述】:
在我的 Unity 游戏中,您可以在地形表面放置各种对象,当放置新对象时,我需要将时间戳保存在文件中。我有保存系统工作,在一些帮助下,我能够从服务器获取时间戳。看来您必须使用 IEnumerator 才能从服务器获取数据,但这给我带来了一个新问题。由于 IEnumerator 不是一个函数,它不能简单地返回任何东西。而且由于它不能返回任何东西,我需要一种解决方法将时间戳从 IEnumerator 传递回它被要求的位置。我计划如何获得时间戳:
int _timestamp = ServerTime.Get();
这样我就可以轻松存储它了
gameObject.GetComponent<_DrillStats>().timestamp = _timestamp;
gameObject.GetComponent<_OtherStats>().timestamp = _timestamp;
gameObject.GetComponent<_EvenMoreStats>().timestamp = _timestamp;
这里是接收时间戳的完整代码:
using UnityEngine;
using System;
using System.Collections;
public class ServerTime : MonoBehaviour
{
private static ServerTime localInstance;
public static ServerTime time { get { return localInstance; } }
private void Awake()
{
if (localInstance != null && localInstance != this)
{
Destroy(this.gameObject);
}
else
{
localInstance = this;
}
}
public static void Get()
{
if (time == null)
{
Debug.Log("Script not attached to anything");
GameObject obj = new GameObject("TimeHolder");
localInstance = obj.AddComponent<ServerTime>();
Debug.Log("Automatically Attached Script to a GameObject");
}
time.StartCoroutine(time.ServerRequest());
}
IEnumerator ServerRequest()
{
WWW www = new WWW("http://www.businesssecret.com/something/servertime.php");
yield return www;
if (www.error == null)
{
int _timestamp = int.Parse (www.text);
// somehow return _timestamp
Debug.Log (_timestamp);
}
else
{
Debug.LogError ("Oops, something went wrong while trying to receive data from the server, exiting with the following ERROR: " + www.error);
}
}
}
【问题讨论】:
-
这是this 的副本。
Action参数的答案就是您要寻找的答案。 -
已更改为:
time.StartCoroutine (time.ServerRequest (www, (status) => { print (status.ToString ()); }));和IEnumerator ServerRequest(WWW www, Action<int> callback) { yield return www; if (www.error == null) { int _timestamp = int.Parse (www.text); callback (_timestamp); } else { Debug.LogError ("Oops, something went wrong while trying to receive data from the server, exiting with the following ERROR: " + www.error); } }但我仍然不明白如何将给定的时间戳传递回需要它的其他脚本。 -
我不知道上面怎么格式化
标签: c# unity3d server timestamp