在我的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);
}
}
}
答案 0 :(得分:3)
这就是我在评论部分的意思:
public static void Get(Action<int> callback)
{
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(callback));
}
IEnumerator ServerRequest(Action<int> callback)
{
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
callback(_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);
}
}
我将两个函数都设为Action<int>
作为参数。
<强> USGAE 强>:
将ServerTime.Get();
替换为:
ServerTime.Get((myTimeStamp) =>
{
Debug.Log("Time Stamp is: " + myTimeStamp);
gameObject.GetComponent<_DrillStats>().timestamp = myTimeStamp;
gameObject.GetComponent<_OtherStats>().timestamp = myTimeStamp;
gameObject.GetComponent<_EvenMoreStats>().timestamp = myTimeStamp;
});
答案 1 :(得分:1)
您可以将时间戳保存到字段,并在协程完成后访问它。
您可以使用带有bool标志的while循环来等待协程完成。