【问题标题】:Unity3D , C# How to save position of objects and restart them later?Unity3D,C#如何保存对象的位置并稍后重新启动它们?
【发布时间】:2019-08-11 11:47:22
【问题描述】:

尊敬的 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】:

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

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

    【讨论】:

    • 谢谢我如何在起始位置重生相同的对象?
    • 请注意,对于FindComponentsOfType,必须启用相应的组件并且 GameObjcts 在层次结构中处于活动状态。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 2022-12-18
    • 2018-12-15
    相关资源
    最近更新 更多