gpt4 book ai didi

c# - Unity3D,C#如何保存对象的位置并稍后重新启动它们?

转载 作者:太空宇宙 更新时间:2023-11-03 22:35:41 25 4
gpt4 key购买 nike

亲爱的 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)

这不会编译,您需要将其与您的数据相匹配,所以但我希望我给了您一个好的起点!

关于c# - Unity3D,C#如何保存对象的位置并稍后重新启动它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55266595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com