read

You can write data in a stream form. Can also use formatted string similar with C or C++.

Open several files for writing like this below. If the file exists, it will be overwritten.

    private List<StreamWriter> _recordFile;

    // Use this for initialization
    void Start()
    {
        _recordFile = new List<StreamWriter>();
        _recordFile.Add(File.CreateText("PlayerRecord" + Random.value));
        _recordFile.Add(File.CreateText("CameraRecord" + Random.value));
    }

Write data like this:

        // Record fire information [10/23/2016 Han]
        dataRecorder.playerFile.Write(Time.time + "\tPlayer fire" + "\tusing weapon:\t" + weapons[weaponID] + "\n");

You can let some game object in the scene to handle all file staff. I put _recordFile into a script named GameDataRecorder. And hang it to a game object in the scene named GameDataRecorder. Finally, open some interfaces to let other script to use the file stream like this:

    public StreamWriter playerFile      // open the interface
    {
        get
        {
            return _recordFile[0];
        }
    }
    public StreamWriter cameraFile
    {
        get
        {
            return _recordFile[1];
        }

    }

In other script that wants to use the file to write can code like this:

    private GameDataRecorder dataRecorder;  // the script manages all data files

    void Start()
    {
        // Get the game data record file from game manager [10/23/2016 Han]
        dataRecorder = GameObject.FindWithTag(Tags.gameController).GetComponent<GameDataRecorder>();
        Debug.Assert(dataRecorder);

    }

And write data like this:

        // Record changing weapon information [10/23/2016 Han]
        dataRecorder.playerFile.Write("\tto:\t" + weapons[weaponID] + "\n");

At last, don’t forget to close the file before application quit.

    void OnApplicationQuit()
    {
        for (int i = 0; i < _recordFile.Count; i++)
        {
            _recordFile[i].Close();
        }
    }
Blog Logo

Honglei Han 韩红雷


Published

Image

Honglei Han 韩红雷的主页

Honglei Han from CUC 中国传媒大学 游戏设计 韩红雷 科研信息 所带课程 个人介绍 开源项目 创作的部分古体诗 Unity 3D 游戏引擎 Game Engine 游戏开发 计算机图形学 虚拟现实 Virtual Reality 程序设计 Programming

Back to Overview