2016-03-05 215 views
0

我使用Unity 5和mono开发进行C#编辑。我有一个C#文件,它读取CSV文件并从CSV内的内容创建一个字符串。我把这个类作为一个带有公共字符串变量的公共类,因为我想能够在另一个类中访问这个字符串变量。这里的CSV阅读器类:使用Unity 5访问另一个C#类的公共变量

using UnityEngine; 
using System.Collections; 
using System.IO; 

public class ReadText : MonoBehaviour{ 
    public TextAsset textFile;  // drop your file here in inspector 
    public string text = ""; 

    void Start(){ 
     string text = textFile.text; //this is the content as string 
     Debug.Log(text); 
    } 
} 

这个类的工作正常。按照预期,我在Unity控制台上运行Debug.Log(文本)输出。

下面是我试图从访问的ReadText类公共文本的其他类:

public class CreateLevel : MonoBehaviour { 

    void Start() { 

     //First, access the text that was read into the ReadText Class (from CSV file) 
     //Find the object "Level Designer" that has the ReadText.cs script attached to it 
     GameObject designer = GameObject.Find("LevelDesigner"); 

     //Get a component of the ReadText Class and assign a new object to it 
     ReadText CSVText = designer.GetComponent<ReadText>(); 

     //Now you can access the public text file String 
     string levelString = CSVText.text; 
     print(levelString); 

     //Second, identify each individual text, line by line. As each text symbol is identified 
     //place the corresponding sprite on the allocated space in the game scene 
     //When the & symbol is encoutered, go to the next line 
     //do all this while there are text symbols, once we have the "!" symbol, we're done 
     print(text); 
     print("We're inside of CreateLevel Class! :C)"); 

    } 
} 

的CreateLevel C#文件附加到场景中的一个空对象。 Unity运行时没有问题,但我没有从Debug.Log或该类的print(text)命令获得输出,所以我在这里丢失了一些东西。任何帮助都会很棒。

+1

你开始中创建一个新的文本变量。 “全局”文本不会被分配,并且本地文本在启动结束时被销毁。删除开始内部文本前面的字符串。而且两个都是在开始时完成的,你不能确定哪个会先运行。 – Everts

+0

从Unity Inspector窗格中为公共“textFile”分配一个文件。这个分配的文件是一个CSV文件。我需要从CreateLevel类访问这个组件,我不认为我是从上面的初始版本开始的。我会在下面的评论中写下解决方案。 – user6020789

回答

0

下面是最终的解决方案。我认为我的问题是公共TextAsset(“textFile”变量)没有从CreateLevel类访问。请参阅YouTube上的AwfulMedia教程:Unity C#教程 - 访问其他类(第5部分)。我希望这不会降级我堆栈溢出,只是想在应得的功劳。我接受了这个教程并为我的目的进行了修改。

这里是新的ReadText类:

public class ReadText: MonoBehaviour { 
    public TextAsset textFile; 
    //text file to be read is assigned from the Unity inspector pane after selecting 
    //the object for which this C# class is attached to 

    string Start(){ 
     string text = textFile.text; //this is the content as string 
     Debug.Log(text); 
     return text; 
    } 
} 

而且新CreateLevel类

public class CreateLevel : MonoBehaviour { 
    //variables needed for reading text from the level design CSV file 
    private ReadText readTextComponent; 
    public GameObject LevelDesigner; 
    public string fileString; 

    // Use this for initialization 
    void Start() { 
     readTextComponent = LevelDesigner.GetComponent<ReadText>(); 
     fileString = readTextComponent.textFile.text; 
     //accesses the public textFile declared in the ReadText class. Assigns the textFile 
     //text string to the CreateLevel class fileString variable 

    } 
}