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

问题描述 投票:1回答:1

亲爱的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# object unity3d positioning
1个回答
3
投票

由于您的对象是MonoBehaviours,您可以使用

ObjectController[] cs = FindComponentsOfType<ObjectController>();

编辑:你也必须从MonoBehaviour中调用它!

如果你的意思是将它保存在hdd上,我不知道“你以后重新启动它们”的确切含义:

你可以用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)

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

© www.soinside.com 2019 - 2024. All rights reserved.