首页 > 解决方案 > 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;
    }


}

非常感谢您的帮助。

标签: c#objectunity3dpositioning

解决方案


由于您的对象是 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)

这不会编译你需要将它适合你的数据,所以但我希望我给你一个好的起点!


推荐阅读