我如何从文本文件中读取我的玩家和武器位置。我希望当游戏开始自动加载它们时

时间:2016-05-01 19:27:52

标签: c# unity3d

我有一个文本文件,其中有四行称为位置,已经写入了位置并用逗号分隔。

我尝试运行我的代码,但我在dataline.ReadLine(dataline)上收到错误说:

  

类型////`string'不包含`ReadLine'的定义,并且找不到类型为`string'的extensiomethod` // ReadLine'(你是否缺少using指令//或汇编引用? )

using UnityEngine;
using System.Collections;
using System.IO;
public class InitializeLevel : MonoBehaviour
{
    private StreamReader sr;
    public string filename;

    void LoadPositions(string filename)
    {
//Using a try catch block.
        try
        {
            sr = new StreamReader(Application.dataPath + "/" + filename);
            string dataline = "";
            while (dataline != null)
            {
               dataline.ReadLine(dataline);
                string[] values = dataline.Split(',');
                Vector3 pos = Vector3.zero;
                pos.x = float.Parse(values[1]);
                pos.y = float.Parse(values[2]);
                pos.z = float.Parse(values[3]);

                GameObject Player = (GameObject)Instantiate(Resources.Load(values[0]));
                Player.transform.position = pos;
            }
        }
        catch (IOException e)
        {
            Debug.Log(e.Message);
        }
        finally
        {
            if (sr != null)
                sr.Close();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

正如评论中已经说过的那样,正确的方法是

        sr = new StreamReader(Application.dataPath + "/" + filename);
        string dataline = "";
        while ((dataline = sr.ReadLine()) != null)
        {
            string[] values = dataline.Split(',');
            Vector3 pos = Vector3.zero;
            pos.x = float.Parse(values[1]);
            pos.y = float.Parse(values[2]);
            pos.z = float.Parse(values[3]);

            GameObject Player = (GameObject)Instantiate(Resources.Load(values[0]));
            Player.transform.position = pos;
        }