c# - Unity3D,C#如何保存对象的位置并稍后重新启动它们?
问题描述
亲爱的 StackOverFlow 社区,
在保存数组中对象的当前位置方面,我再次需要您的帮助。我需要保存它,因为我想重新启动关卡并将它们的对象重新定位到起始位置。我不知道我该怎么做..这是我的对象代码,它们随着游戏的进行而移动,所以我需要保存对象的位置..
这是我移动对象的代码,该代码在每个移动的对象中。
public class ObjectController : MonoBehaviour {
public bool moving = false;
public float speed = 1f;
private bool signaledToMove = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
if( moving && signaledToMove ){
this.GetComponent<Rigidbody>().AddForce( Vector3.back * 250 * speed );
}
// Destroy object to save perforomance, if it got out of the scene.
if( this.gameObject.transform.position.z < -520 ||
this.gameObject.transform.position.y < -20 )
Destroy(this.gameObject);
}
public void SignalToMove(){
this. signaledToMove = true;
}
}
非常感谢您的帮助。
解决方案
由于您的对象是 MonoBehaviours,您可以使用
ObjectController[] cs = FindComponentsOfType<ObjectController>();
编辑:您也必须从 MonoBehaviour 调用它!
如果您的意思是将其保存在硬盘上,我不知道您对“稍后重新启动”的确切含义:
你可以使用Json!为此,您必须在以下结构中拥有所有可保存的数据:
struct DataStruct { Vector3[] positions }
DataStruct data = (insert your data here);
string dataString = JsonUtility.ToJson<DataStruct>();
// this saves the struct on the hdd
System.IO.File.WriteAllText(your data path);
// this reads the file
string datareconstructed = System.IO.File.ReadAllText(path);
// this struct will contain all the previously saved data
// you just need to set the positions from it to you objects again
DataStruct dataReco = JsonUtility.FromJson<DataStruct>(datareconstructed)
这不会编译你需要将它适合你的数据,所以但我希望我给你一个好的起点!
推荐阅读
- javascript - 如何创建从零计数到 HTML 中包含的元素的 Javascript PURE 动画?
- pycharm - PyCharm:为什么它会收集我的个人数据
- python - 打印两个字符串中同一位置不同的特定字符
- typescript - 配置/路由映射的装饰器如何工作(TypeScript 和 Loopback4)?
- python - Tkinter: Remove 2 characters from the end of a index
- java - 如何使用 Android 和 iOS 的本机代码解压缩 zip 文件?
- javascript - 将 HTML 画布保存到 WooCommerce 用户帐户
- bash - 如果程序失败,powershell 脚本将停止(如 bash `set -o errexit`)
- python - 使用 Numba 加速滚动均方根偏差计算
- javascript - 如何获取当前页面 URL 并使用它