Example #1
0
    // this function registers all the vehicle's pieces' data into the corresponding file
    public void Save()
    {
        FileStream file = File.Create(MainManager.GetSavePath() + saveName);         // if a file already exists, the File.Create() will simply rewrite it

        if (file == null || !file.CanRead)
        {
            Debug.LogError("COULD NOT CREATE FILE " + MainManager.GetSavePath() + saveName);
            return;
        }

        Transform[] pieces = GetComponentsInChildren <Transform>();        // we get all pieces

        // the noise corresponds to the objects we don't want to save,
        // such as the root component, which is not a piece, and the base
        int noise = 0;

        foreach (Transform tr in pieces)
        {
            if (tr.tag != "Piece" || tr.name == "Base")
            {
                noise++;
            }
        }

        BinaryWriter writer = new BinaryWriter(file);

        writer.Write(pieces.Length - noise);         // we register the number of pieces there is, so that we know how many we'll have to load

        foreach (Transform tr in pieces)
        {
            // then for every correct piece we simply register the name (to know what piece this is),
            // the position and the rotation (useful for pieces like weapons or boosters)
            if (tr.tag == "Piece" && tr.name != "Base")
            {
                writer.Write(tr.name);
                writer.Write(tr.position.x);
                writer.Write(tr.position.y);
                writer.Write(tr.position.z);
                writer.Write(tr.rotation.x);
                writer.Write(tr.rotation.y);
                writer.Write(tr.rotation.z);
                writer.Write(tr.rotation.w);
            }
        }

        writer.Close();
        file.Close();

        // we add the save to a file that references all saves, so that we only have to read this file to know all saved vehicles
        MainManager.AddSaveName(saveName);
    }