Search code examples
c#objectunity-game-enginepositioning

Unity3D , C# How to save position of objects and restart them later?


Dear StackOverFlow community,

I need again your help in field of saving current position of objects in array. I need to save it because I want to restart level and their object to start position. I don't have idea how i can do it .. This is my code of objects and they moving as game proceed so I need to save position of the objects..

This is my code to move object and that code is in every objects that moving..

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;
    }


}

Thank you so much for help.


Solution

  • Since your objects are MonoBehaviours you can use

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

    Edit: you must call this from a MonoBehaviour too!

    I dont know exactly what you mean with "restart them later" if you mean saving it on hdd:

    your can use Json! for that you must have all saveable data in structs like:

    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)
    

    this wont compile you need to fit this to your data and so but i hope i gave you a good starting point!